[LeetCode] 191. Number of 1 Bits 二进制数1的个数
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
写一个函数操作无符号整数,返回整数的二进制数1的个数。
解法:位操作Bit Manipulation
使用n&(n-1)的方法
假使 n =0x110101
n n-1 n&(n-1)
step1: 110101 110100 110100
step2: 110100 110011 110000
step3: 110000 101111 100000
step4: 100000 011111 000000
发现有几个1,就循环几次n&(n-1)得到0。
时间复杂度:O(M),M是n中1的个数
Java:
1 2 3 4 5 6 7 8 9 10 | public class Solution { public int NumberOf1( int n) { int count = 0 ; while (n != 0 ) { n &= (n - 1 ); count ++; } return count; } } |
Python:
1 2 3 4 5 6 7 8 9 | class Solution: # @param n, an integer # @return an integer def hammingWeight( self , n): result = 0 while n: n & = n - 1 result + = 1 return result |
Python:
1 2 3 4 5 6 7 8 9 10 11 | class Solution( object ): def hammingWeight( self , n): """ :type n: int :rtype: int """ res = 0 while n: res + = (n& 1 ) n >> = 1 return res |
Python:
1 2 3 4 5 6 7 8 | class Solution( object ): def hammingWeight( self , n): """ :type n: int :rtype: int """ b = bin (n) return b.count( '1' ) |
C++:
1 2 3 4 5 6 7 8 9 10 11 | class Solution { public : int hammingWeight(uint32_t n) { int res = 0; for ( int i = 0; i < 32; ++i) { res += (n & 1); n = n >> 1; } return res; } }; |
C++:
1 2 3 4 5 6 7 8 9 10 | class Solution { public : int hammingWeight(uint32_t n) { int count = 0; for (; n; n &= n - 1) { ++count; } return count; } }; |
类似题目:
[LeetCode] 190. Reverse Bits 翻转二进制位
All LeetCode Questions List 题目汇总
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步