###### tags: `Leetcode` `easy` `bit` `python` `c++` # 191. Number of 1 Bits ## [題目連結:] https://leetcode.com/problems/number-of-1-bits/ ## 題目: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3. ![](https://i.imgur.com/EOkHyqP.png) #### [圖片來源:] https://leetcode.com/problems/number-of-1-bits/ ## 解題想法: 兄弟題目: [190. Reverse Bits](/rGFkEUTqTCmcJmMfmRiHwA) 取最後一位: 某數&1 ## Python: ``` python= class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ ans = 0 while n: #若n 最後一碼為0 則不會進入迴圈 if (n&1) : ans = ans +1 #n向右移 n = n >> 1 return ans if __name__ == '__main__': result = Solution() n = int('00000000000000000000000000001011',2) ans = result.hammingWeight(n) print(n,ans) ``` ## C++: ``` cpp= #include<iostream> using namespace std; class Solution { public: int hammingWeight(uint32_t n) { int res=0; while (n){ if (n&1) res+=1; n>>=1; } return res; } }; int main(){ Solution res; // 0bxxxxxx binary string representation uint32_t n= 0b00000000000000000000000000001011; int ans=res.hammingWeight(n); cout<<ans<<endl; return 0; } ```