Topic description:
Input an integer and output the number of 1's in the binary representation of the number. Negative numbers are represented in complement.
Problem solving plan:
for(int i=0; i<32; i++){ t = (n & 0x80000000 >>> i) >>> (31-i); if(t > 0) totalOf1 ++; }Split this code. To understand this shift output problem, you need to understand the following:
* 0x80000000 is the hexadecimal representation of the number, and the binary representation is 1000000000000000000000000000000
* The priority of the operation, the shift operation is higher than Logical operation, >>> higher than &
* bit logical AND operation 1&1 = 1, 0&1 = 0
* >>> unsigned right shift, part of the shift is discarded, and the left bit is filled with 0;
the execution sequence of the statement block of the for loop:
1. 0x80000000 unsigned right shift i bits;
2, n and 1 result bitwise AND;
3, 2 result unsigned right shift 31-i bits
4, output 3 result
The difference between >> and >>>:
>>: Signed right shift . A positive number is shifted to the right and the high-order position is filled with 0, and a negative number is shifted to the right and the high-order position is filled with 1. for example:
4 >> 1, the result is 2; -4 >> 1, the result is -2. -2 >> 1, the result is -1.
>>>: Unsigned right shift . Whether it is a positive or negative number, the high bits are filled with 0.
For positive numbers, >> and >>> are no different.
For negative numbers, -2 >>> 1, the result is 2147483647 (Integer.MAX_VALUE), and -1 >>> 1, the result is 2147483647 (Integer.MAX_VALUE).
Code:
import java.util.Scanner; public class NumberOf1 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ int n = in.nextInt(); int result = numberOf1(n); System.out.println(result); } } public static int numberOf1(int n){ int t = 0; int totalOf1 = 0; for(int i=0; i<32; i++){ t = (n & 0x80000000 >>> i) >>> (31-i); if(t > 0) totalOf1 ++; } return totalOf1; } }