Count number of binary ones in an Integer using Java

//To count the number of ones in a Integer we can either use brute force O(n) or

//we can ‘AND’ the number with number-1 until num becomes zero

//keep a count for how many times the loop runs whic is the ans

public class bit {

 

public static void main(String [] args)

{

int a = 5;

int b = 6;

int count = 0;

int c;

for(c = a ^ b; c != 0; c = c >> 1)

{

count += c & 1;

}

System.out.println(count);

}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s