其他分享
首页 > 其他分享> > 剑指 Offer 15. 二进制中1的个数

剑指 Offer 15. 二进制中1的个数

作者:互联网

题目链接: leetcode.

时间复杂度 O(log_2 n)
此算法循环内部仅有 移位、与、加 等基本运算,占用 O(1);逐位判断需循环 log_2 n次
空间复杂度 O(1)

注意:只写n>>1;是没用滴,要再赋值n >>= 1;

/*
执行用时:4 ms, 在所有 C++ 提交中击败了39.61%的用户
内存消耗:5.9 MB, 在所有 C++ 提交中击败了83.28%的用户
*/ 
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans = 0;
		while(n)
		{
			ans += n & 1;
			n = n >> 1;  
		} 
		return ans;
    }
};

看大佬的题解,n&(n-1)可太巧妙了,每次都消去最右边的1,消到n为0一共消去几个1答案就是几

/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:5.8 MB, 在所有 C++ 提交中击败了97.64%的用户
*/ 
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int ans = 0;
		while(n)
		{
			n = n & (n - 1);
			ans++;
		} 
		return ans;
    }
};

据说还能判断二的幂,试了一下子 : 231. 2的幂.

/*
执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户
内存消耗:5.8 MB, 在所有 C++ 提交中击败了78.62%的用户
*/
class Solution {
public:
    bool isPowerOfTwo(int n) {
        if(n <= 0)//注意要判断等于0 
            return false;
        return !(n & (n - 1));
    }
};

如何获取二进制中最右边的 1:x & (-x)

  • 保留最右边的 1并将其他的位设置为 0
  • (-x) = ~x + 1, ~x表示所有位取反

如何将二进制中最右边的 1 设置为 0:x & (x - 1)

标签:15,击败,Offer,二进制,用户,C++,int,提交,ans
来源: https://blog.csdn.net/pppppppyl/article/details/113755317