## A9 Interview Question

Software Engineer / Developers**Team:**Search

**Country:**United States

**Interview Type:**In-Person

{ public static int getNumOnes(int val)

{

int count = 0;

if(val<=0)

return count;

else

{

int mask=0X0001;

while(val!=0)

{

int c = mask & val;

{

if(c == 1)

count++;

val=val>>>1;

}

}

}

return count;

}}

```
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int count_SetBit=countSetBit(num);
System.out.println(count_SetBit);
}
public static int countSetBit(int num)
{
int count=0;
int mask=0x0001;
while(Math.abs(num)>0)
{
if((num&mask)==1)
count++;
num>>>=1;
}
return count;
}
```

}

This Solution works for negative and positive number both.

C# using Math.Pow function. Not as sexy as the other solutions, but it works :)

```
protected int NumberOfOnes(int anInt)
{
int retVal = 0;
int pow = 0;
while (Math.Pow(2,pow) <= anInt)
pow++;
while (pow >= 0) {
if (anInt >= Math.Pow(2,pow)) {
anInt -= (int)Math.Pow(2,pow);
retVal++;
}
pow--;
}
return retVal;
}
```

```
private int count(int val) {
int ret = 0;
while(val > 0) {
val&=(val-1);
ret++;
}
return ret;
}
```

this actually works for positive numbers. negative numbers's 1s can be cumbersome to calculate though..

yes, you are right. depending on whether number int or long, we can do the following then:

```
int count = 0;
for(int i=0;i<len;i++){//where len = 32 if int, 64 otherwise
if ((n & (1 << i)) > 0){
count++;
}
}
count+=(n >> (len-1)) & 1;
```

This solution does not even scale for positive numbers.

Lets consider val = 1001

The result from tour code returns 7, but the actual result is 6.

This link has code which counts it for both positive and negative numbers.

- codechamp March 30, 2014onestopinterviewprep.blogspot.com/2014/03/count-1s-in-binary-format-of-number.html

Enjoy :)