Get the binary number of an integer and get the number of 1s
There is such a question in Jianzhi offer:
Input an integer n, and output the number of 1s in the 32-bit binary representation of the number. Negative numbers are expressed in two's complement.
Example 1
Input:
10
Return value:
2
Explanation:
The 32-bit binary representation of 10 in decimal is 0000 0000 0000 0000 0000 0000 0000 1010, in which there are two 1s.
Example 2
Input:
-1
Return value:
32
Explanation:
Negative numbers are represented by complement code, and the 32-bit binary representation of -1 is 1111 1111 1111 1111 1111 1111 1111 1111, of which 32 are 1
train of thought
So how to get the binary representation of an int integer?
Use the toBinaryString method of Integer:
String b = Integer.toBinaryString(n);//Convert to Binary
What you get at this point is a string, you can split it into an array:
char[] chars = b.toCharArray();
In this way, you can use the for loop to find the number of 1s!
the code
public int NumberOf2(int n){
String b= Integer.toBinaryString(n);//转化为二进制
char[] chars = b.toCharArray();
int count=0;
for(int i=0;i<chars.length;i++){
if('1'==chars[i]){
count++;
}
}
return count;
}
Because negative numbers in Java are originally expressed in complement codes, they can be manually converted out of order, and can be traversed directly with a for loop.
another code
public int NumberOf1(int n) {
// 定义计数器
int count=0;
// int类型是32位,所以循环32次
for(int i=0;i<32;i++){
// 每一次都要检查末位是否为1
if( (n&1)==1 ){
count++;
}
// 右移一位(使用无符号右移,补码最高位补0而不是1,所以最多循环32次)
n = n>>>1;
}
return count;
}
This is a java displacement operation. Java bit operations are operations with very high execution efficiency. Sometimes it will have a miraculous effect in brushing questions. However, bit operations are still not easy to understand. Here are two commonly used bit operations.
- n&1: AND operation, to judge whether the binary rightmost bit of n is 1.
- n>>1: Shift operation, delete the rightmost bit of the binary of n.
- n>>1 is a signed right shift, n>>>1 is an unsigned right shift.