NumberOf1Bits(leetcode191)

rite a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).java

Example 1:測試

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

Example 2:code

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

使用APIip

public static int hammingWeight(int n) {
     return Integer.bitCount(n);
}

API裏面寫的沒看懂,本身寫寫get

//在java中不能定義unsign int 用long類型代替 測試2147483648
public static int hammingWeight2(long n) {
    int num = 0;
    while(n > 0) {
        num += n & 1;
        n = n >>> 1;
    }
    return num;
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息