Amazon Interview Question: Number of 1's in binary repre... | Glassdoor

## Interview Question

Software Development Engineer Interview Seattle, WA

# Number of 1's in binary representation of integer?

Tags:
programming, algorithm

2

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

Interview Candidate on Jun 8, 2009
8

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

uffe hellum on Jun 9, 2009
1

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

uffe hellum on Jun 9, 2009
0

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....

funny on Jul 13, 2009
2

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

Anonymous on Jul 27, 2009
0

Several of the above work, but use preincrement

2

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

Ben on Oct 4, 2009
1

do { sum += n&amp;1; } while (n&gt;&gt;=1);

maxzed2k on Feb 10, 2010
0

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 on Mar 21, 2010
0

Lets consider 14(1110) is the number

int CountOnes(int Number)
{
int n=0;
while(number !=0)
{
if(number%2==1) n++;
number &gt;&gt; 1;
}
return n;
}

pavan on Dec 22, 2010
0

The function takes an int and returns the number of Ones in binary representation

public static int findOnes(int number)
{

if(number &lt; 2)
{
if(number == 1)
{
count ++;
}
else
{
return 0;
}
}

value = number % 2;

if(number != 1 &amp;&amp; value == 1)
count ++;

number /= 2;

findOnes(number);

return count;
}

Roshan on May 3, 2013
0

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 on Mar 30, 2015
0

int num = 31;
int counter = 0;

{
{
counter++;
}