Amazon Interview Question

Number of 1's in binary representation of integer?

Interview Answers

Anonymous

Jun 10, 2009

unsigned int ones(unsigned int number) { unsigned int n; for (n = 0; number != 0; number >> 1) { if (number & 1) { n++; } } return n; }

8

Anonymous

Jun 10, 2009

unsigned int ones(unsigned int number) { unsigned int n; for (n = 0; number != 0; number >> 1) { if (number & 1) { n++; } } return n; }

1

Anonymous

Jul 27, 2009

ct = 0; while (val) { ct++; val = val & (val - 1); }

2

Anonymous

Oct 4, 2009

public static int population(int x) { x = (x & 0x55555555) + ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F); x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF); x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF); return x; }

2

Anonymous

Feb 11, 2010

in C++, how about: do { sum += n&1; } while (n>>=1);

1

Anonymous

Jun 9, 2009

Run a loop, in which you binary-AND the integer with 1, and increment a counter, if the result is 1. Then right-shift the input-integer by 1 bit, and start over in the loop

2

Anonymous

Mar 1, 2018

int num = 31; int mask = 1; int counter = 0; while (num > mask ) { if ((num & mask) == mask) { counter++; } mask = mask << 1; } Console.Write(counter); Console.ReadKey();

Anonymous

Dec 22, 2010

Lets consider 14(1110) is the number int CountOnes(int Number) { int n=0; while(number !=0) { if(number%2==1) n++; number >> 1; } return n; }

Anonymous

May 3, 2013

The function takes an int and returns the number of Ones in binary representation public static int findOnes(int number) { if(number < 2) { if(number == 1) { count ++; } else { return 0; } } value = number % 2; if(number != 1 && value == 1) count ++; number /= 2; findOnes(number); return count; }

Anonymous

Mar 30, 2015

All the answers above will not get you to amazon... try code the function with o(m), where m is the number of 1's in the binary representation of an integer. (hint: look up "Programming Interviews Exposed")

Anonymous

Mar 21, 2010

int ones( ) { int n; int number = 1100110111; n = 0; while (number!=0) { int temp = number % 10; if(temp ==1 ) n++; number = number/10; } return n; }

Anonymous

Sep 22, 2009

Several of the above work, but use preincrement

Anonymous

Jul 14, 2009

i dnt knw wheather it correct or not.....do correct me if im wrng a=0 q=n/2 r=n%2 n=q if(r=1)then a=a++ continue....