【剑指offer】15. 二进制中1的个数

120 阅读2分钟

题目描述

在这里插入图片描述 在这里插入图片描述

// 力扣
// 请实现一个函数,输入一个整数(以二进制串形式),输出该数二进
// 制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 
// 1。因此,如果输入 9,则该函数输出 2。

// 牛客
// 输入一个整数,输出该数32位二进制表示中1的个数。其中负数用补码表示。

题解

/////////////////////////////// 逐次运算 ///////////////////////////////

// 牛客
// 无法通过测试,超出时间限制
public class Solution {
    public int NumberOf1(int n) {
        if (n == 0)
            return 0;
        int index = 1;
        int count = 0;
        while (index != 0)
            if ((index & n) != 0)  // 与运算找1,如果当前位是0,与运算结果就是0,count不会递增
                count++;
            index = index << 1;  // index二进制整体左移一位
        return count;
    }
}
////////////////////////////// 末位相消 //////////////////////////////


// 最好还是用这种末位相消的方法来通过测试
// 假如一个二进制数010100,减1之后为010011,
// 可以看到,原来最右边的1变成了0
// 原来最右边的1再往右的所有0全变成了1。
// 如果让010100和010011做与运算,得到010000,
// 和原来010100比,010000最右边的1被与运算相消了
// 所以其实一个数n和n-1做与运算,可以消掉n最右边的1。

// 牛客
// 运行时间:10ms
// 占用内存:9556k
public class Solution {
	public int NumberOf1(int n) {
		if (n == 0)
			return 0;
		int count = 0;
		while (n != 0) {
			n = n&(n-1);
			count++;
		}
		return count;
	}
}

// 力扣
// 执行用时:1 ms, 在所有 Java 提交中击败了98.11%的用户
// 内存消耗:35.7 MB, 在所有 Java 提交中击败了43.89%的用户
public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
		if (n == 0)
			return 0;
		int count = 0;
		while (n != 0) {
			n = n&(n-1);
			count++;
		}
		return count;
    }
}