+ 1
Pls help with code coach Number of ones
Please explain what's happening in this code and also if there is any other alternative besides this code. import java.util.Scanner; class countSetBits { static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } public static void main(String args[]) { Scanner s = new Scanner(System.in); int i = s.nextInt(); System.out.println(countSetBits(i)); } }
5 Respuestas
+ 1
Devishree
n & 1 returns the last bit binary value of the number n .
See for example :
5 => 101 => 5&1 returns 1
4 => 100 => 4&1 return 0
If you observe that even numbers will have 0 at right most bit. Odd numbers will have 1 as right most bit of binary value. So this is logic to determine if the number is even or odd by bitwise-and '&' operator.
5 & 1 =>
101
001
___
001
4&1 =>
100
001
___
000
count += n&1; here 'count' will have odd numbers count.
n >>= 1 is bit wise right shift operator, will shift 1 bit to it's right position in binary places so actually it's equal to
n=n/2 ;
So example input 10 =>
10&1 => 0 , n=10/2 => 5
5&1=> 1 , n= 5/2 => 2
2&1 => 0 , n= 2/2 => 1
1&1=> 1 , n= 1/2 => 0
Loop gets terminated as n >0 false.
Count will have value 2, will ne returned..
Hope it helps....
if there any other issues, you can reply..
+ 3
In C#, you may find it easy
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
string binary = Convert.ToString(n, 2);
Console.WriteLine(binary);
Console.WriteLine(binary.Count(x => x == '1'));
}
+ 1
Add details about task or description..
+ 1
Jayakrishna🇮🇳 Done. I have added the code.
+ 1
Jayakrishna🇮🇳 I have understood... Thank you 😊