Google Interview Question
Software Engineer / DevelopersCountry: United States
int main ()
{
int n ;
int count = 0;
printf("Enter the number: " );
scanf ("%d", &n);
while(n) {
if(n&1 ) {
count ++;
}
n = n>>1;
}
printf("The number of 1's in the number are : %d\n", count);
return 0;
}
you can do this using bit manipulations:
smth like:
x = (x & 0x55555555) + ((x & 0xaaaaaaaa) >> 1); // # of 1's in every 2 bits
x = (x & 0x33333333) + ((x & 0xcccccccc) >> 2); // # of 1's in every 4 bits
x = (x & 0x0f0f0f0f) + ((x & 0xf0f0f0f0) >> 4); // # of 1's in every 8 bits
and so on..
some optimizations also possible on the last steps
There's a 2nd part to the question as well !
Testing the function:
1. Int Range Test (feeding numbers greater than the 32 bit limit of INT)
2. Negative numbers test
Other suggestions ?
Using bit shifting:
def countbits(n):
count = 0
while(n):
count += 1 & n
n >> 1
return count
Or using properties of binary:
def countbits(n):
count = 0
while(n):
n = n & (n - 1)
return count
Or you could do something recursive:
def countbits(n):
if n == 0:
return n
return (1 & n) + countbits(n >> 1)
Or even (though not as pretty):
def countbits(n):
if n != 0:
n = (1 & n) + countbits(n >> 1)
return n
/*Contract: Number -> Number
* Purpose: It will return no. of one's in the binary representation of the
* given no.
* Example: See Tests
* Strategy:Generative recursion */
public static int NumberOfOnes(int iVal){
//int i =iVal;
int ans =0;
if(1==(iVal % 2))
ans++;
while(!(0==iVal || 1==iVal)){
iVal=iVal/2;
if(1==(iVal % 2))
ans++;
}
return ans;
}
“How will you test this function” is the key point of the question.
So before writing code, we need to consider the possible exceptions. Obviously, here the integer could be positive, negative or 0. So the code should deal with all those conditions. The way of right shifting repeatedly is not available for negative integers because they are represented by complement + 1. So we can use left shifting. The code is shown as follows
public static int count(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n&flag) != 0)
count++;
flag = flag<<1;
}
return count;
}
“How will you test this function” is the key point of the question.
So before writing code, we need to consider the possible exceptions. Obviously, here the integer could be positive, negative or 0. So the code should deal with all those conditions. The way of right shifting repeatedly is not available for negative integers because they are represented by complement + 1. So we can use left shifting. The code is shown as follows
public static int count(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((n&flag) != 0)
count++;
flag = flag<<1;
}
return count;
}
count = 0;
- Anonymous December 21, 2011while(n = n&(n-1))
count++;