This question is still written in the time encountered, did not think too much, direct use of the most direct shift addition method, although the results can be obtained, but the program efficiency is low.
Later discovered that using n=n& (n-1) method, the efficiency will be higher, the first code.
<span style= "FONT-SIZE:18PX;" >public static void Main (string[] args) {
//TODO auto-generated method stub
Scanner Scanner = new Scanner (Syst em.in);
int n = scanner.nextint ();
int count = 0;
while (n!= 0)
{
count++;
n=n& (n-1);
}
System.out.println (count);
}
</span>
Analysis: The while loop only needs to execute 1 of the number of n + 1 times. Take n=19 as an example, the binary number is: 0001 0011
First cycle: 0001 0011 & 0001 0010 = 0001 0010
Second cycle: 0001 0010 & 0001 0001 = 0001 0001
Cycle number three: 0001 0001 & 0001 0000 = 0001 0000
Fourth cycle: 0001 0000 & 0000 1111 = 0000 0000, at this time n=0, jump out of the loop.