Title Description
An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.
Ideas analysis
- Let integer and
1
phase can be judged integer binary representation of whether the rightmost one1
, the one left after another and integer phase , you can compare the second from the right, comparing the cycle, you can count the binary1
number
(may generally think of an integer to the right , and then after1
phase, but this approach will fall into an infinite loop when incoming negative, because negative right shift operation will be supplemented at a high level1
, instead0
) - After a integer minus 1 and then the original integer phase , then the binary integer in the rightmost 1 becomes 0, until the whole numbers 0, you can count the number of 1s.
Test Case
- Positive (inclusive 1,0x7FFFFFFF)
- Negative (inclusive 0x80000000,0xFFFFFFFF)
- 0
## the Java Code
public class Offer15 {
public static void main(String[] args) {
System.out.println("测试正数-->");
test1();
System.out.println("测试负数-->");
test2();
System.out.println("测试0-->");
test3();
}
public static int NumberOf1(int n) {
return Solution3(n);
}
/**
* 解法一: 思路: 上面的思路是移动 整数,我们可以移动与整数相与的1 ,每次判断之后我们将1 向左移动, 这时判断的就是整数所表示二进制中右边的第二位
*
* @param n
* @return
*/
private static int Solution2(int n) {
int count = 0;
int flag = 1;
while (flag != 0) {
if ((flag & n) != 0) {
count++;
}
flag = flag << 1;
}
return count;
}
/**
* 解法二: 思路 :利用了一种二进制运算的规律,把一个整数减去1之后再和原来的整数做与运算, 得到的结果相当于把整数二进制中最右边的1变为0
*
* @param n
* @return
*/
private static int Solution3(int n) {
int count = 0;
while (n != 0) {
count++;
n = n & (n - 1);
}
return count;
}
/**
* 测试正数
*/
private static void test1() {
System.out.println("0x7FFFFFFF: " + NumberOf1(0x7FFFFFFF));
System.out.println("1: " + NumberOf1(1));
}
/**
* 测试负数
*/
private static void test2() {
System.out.println("0x80000000: " + NumberOf1(0x80000000));
System.out.println("0xFFFFFFFF: " + NumberOf1(0xFFFFFFFF));
}
/**
* 测试0
*/
private static void test3() {
System.out.println("0: " + NumberOf1(0));
}
}