LeetCode-Number of 1 Bits
阿新 • • 發佈:2018-12-19
Description: Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).
Example 1:
Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011
Example 2:
Input: 128 Output: 1 Explanation: Integer 128 has binary representation 00000000000000000000000010000000
題意:計算一個無符號整數二進位制表示中1的數量;
解法:最容易想到的自然就是通過計算其二進位制表示來統計1的數量;不過,這裡我們可以考慮使用位操作,首先我們每次將整數右移一位後再與1相與,判斷結果是否為1即可計算整數二進位制表示特定位上是否為1;
Java
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int result = 0; for (int i = 0; i < 32; i++) { result = ((n >> i) & 0x01) == 1 ? result + 1 : result; } return result; } }