Description:
Input an integer and output the value in binary format. The negative number is indicated by the complement code.
Input:
The input may contain multiple test examples.
For each input file, enter an integer T in the first line, which indicates the number of test samples. Enter an integer for each test sample.
. N must be an integer in the int range.
Output:
Corresponding to each test case,
Output an integer that represents the number of 1 in the input number.
Sample input:
3
4
5
-1
Sample output:
1
2
32
Recommendation index :※※
Source: http://ac.jobdu.com/problem.php? PID = 1, 1513
The number of statistical items 1 is actually the core issue of the bit structure. Http://community.topcoder.com/tc? Module = static & d1 = tutorials & D2 = binaryindexedtrees
Isolating the last digit
Note:Instead of "the last non-zero digit," It will write only "the last digit ."
There are times when we need to get just the last digit from a binary number, so we need an efficient way to do that. LetNumBe the integer whose last digit we want to isolate. In binary notationNumCan be representedA1B,
WhereARepresents binary digits before the last digit andBRepresents zeroes after the last digit.
Integer-NumIs equal(A1B) rows + 1 = A rows 0b rows + 1.BConsists of all zeroes, soB BranchConsists of all ones. Finally we have
-Num = (A1B) Then + 1 = A then 0b then + 1 = A then 0 (0... 0) rows + 1 = A rows 0 (1... 1) + 1 = a limit 1 (0... 0) = A 00001b.
Now, we can easily isolate the last digit, usingBitwiseOperatorAnd(In c ++, Java it is&)NumAnd-Num:
A1B
& A 00001b
--------------------
= (0 .. 0) 1 (0 .. 0)
N & (-N) calculates the last 1 of the numbers.
N-(N & (-n), remove the last 1, repeat the previous step, and repeat the number of repeat times.
# Include <iostream> # include <stdlib. h> # include <stdio. h> using namespace STD; int count_ones (int n) {int sum = 0; while (n! = 0) {n = N-(N & (-N); sum ++;} return sum;} int main () {int t, n; scanf ("% d", & T); For (INT I = 0; I <t; I ++) {scanf ("% d", & N ); printf ("% d \ n", count_ones (n);} return 0 ;}