Sophos Interview Question

1. Write a function (in any programming language) that gets an integer parameter and returns the number of 1 digits in its binary representation. 2. How would you implement this even faster if you had infinite memory and processing capabilities.

Interview Answers

Anonymous

Mar 7, 2015

1. using namespace std; int countOnes(int n) { int ret = 0; while (n > 0) { ret += (n & 1); n >>= 1; } return ret; } 2. Store the answer in a table for all integers and look it up from there.

Anonymous

Mar 9, 2016

In Java, XOR the number with zer and then bits shift count the number of ones. public class BitManipulation { public static void main(String[] args) { // TODO Auto-generated method stub findXORBits(6,0); } public static int findXORBits(int x, int y) { int bitCount = 0; int z= x^y; System.out.println(z); while (z != 0) { //increment count if last binary digit is a 1: bitCount += z & 1; z = z >> 1; //shift Z by 1 bit to the right } System.out.println(bitCount); return 0; } }