标签:leetcode
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.
计算一个无符号 32 位整数的二进制表示有多少个 1. 只要每次取最后一位判断是否是 1, 然后进行右移操作就好。复杂度 O(32).
C++:
class Solution { public: int hammingWeight(uint32_t n) { int ans = 0; for(int i = 0;i < 32;++i) { if(n & 1) ans++; n = n >> 1; } return ans; } };
Python:
class Solution: # @param n, an integer # @return an integer def hammingWeight(self, n): ans = 0 for i in range(0,32): ans = ans + (n&1) n = n>>1 return ans
标签:leetcode
原文地址:http://blog.csdn.net/jcjc918/article/details/44489475