[LeetCode] #191 位1的個數
阿新 • • 發佈:2021-09-07
[LeetCode] #191 位1的個數
編寫一個函式,輸入是一個無符號整數(以二進位制串的形式),返回其二進位制表示式中數字位數為 '1' 的個數(也被稱為漢明重量)。
輸入:00000000000000000000000000001011
輸出:3
解釋:輸入的二進位制串 00000000000000000000000000001011 中,共有三位為 '1'。
使用Integer的API
class Solution { public int hammingWeight(int n) { return Integer.bitCount(n); } }
使用&按位計數
public class Solution { public int hammingWeight(int n) {int res = 0; for(int i = 0;i < 32;i++) if((n & 1<<i) != 0) res++; return res; } }
或者
class Solution { public int hammingWeight(int n) { int count = 0; for (int i = 0; i < 32; i++) { count += n & 1; n>>= 1; } return count; } }
n&(n-1) 其運算結果恰為把 n 的二進位制位中的最低位的 1 變為 0 之後的結果
利用這個位運算的性質,運算次數就等於 n 的二進位制位中 1 的個數
public class Solution { public int hammingWeight(int n) { int ret = 0; while (n != 0) { n &= n - 1; ret++; }return ret; } }
知識點:
Integer.bitCount() 把int型別轉換成二進位制,計算二進位制中1的個數。
總結:無