Skip to main content

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

LeetCode 提示

题目难度 简单

原题链接 🔗 leetcode

题解 1.py#

class Solution:    def hammingWeight(self, n: int) -> int:        cnt = 0        bit = 1        while bit <= n:            if n & bit:                cnt += 1            bit <<= 1        return cnt

题解 2_与运算.py#

# n & (n-1) 二进制效果是把n的最后一个1给去掉# 更快class Solution:    def hammingWeight(self, n: int) -> int:        cnt = 0        while n:            n = n & (n-1)            cnt+=1        return cnt