領釦-191 位1的個數 Number of 1 Bits MD
阿新 • • 發佈:2018-12-08
Markdown版本筆記 | 我的GitHub首頁 | 我的部落格 | 我的微信 | 我的郵箱 |
---|---|---|---|---|
MyAndroidBlogs | baiqiantao | baiqiantao | bqt20094 | [email protected] |
領釦-191 位1的個數 Number of 1 Bits MD
目錄
目錄位1的個數 Number of 1 Bits
問題
方式一:字元比較
方式二:取餘運算或位運算
位1的個數 Number of 1 Bits
問題
編寫一個函式,輸入是一個無符號整數,返回其二進位制表示式中數字位數為 ‘1’ 的個數(也被稱為漢明重量)。
Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
示例 :
輸入: 11
輸出: 3
解釋: 整數 11 的二進位制表示為 00000000000000000000000000001011
示例 2:
輸入: 128 輸出: 1 解釋: 整數 128 的二進位制表示為 00000000000000000000000010000000
這個問題,不管是用哪種方式實現,都是最簡單的一道題了。
方式一:字元比較
class Solution {
public int hammingWeight(int n) {
int count = 0;
for (char c : Integer.toBinaryString(n).toCharArray()) {
if (c == '1') {
count++;
}
}
return count;
}
}
方式二:取餘運算或位運算
class Solution {
public int hammingWeight(int n) {
int count = 0;
long l = n & 0xFFFFFFFFL; //轉換為 long 型別,防止負數問題
while (l > 0) {
//if (l % 2 == 1) count++; //取餘運算
if ((l & 1) == 1) count++; //位運算,速度相比取餘運算會快一點
l = l >> 1; //不需要使用 >>>
}
return count;
}
}
類似的實現1:
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
if ((n & 1) == 1) count++;
n = n >>> 1; //必須使用 >>> ,而不能使用 >>
}
return count;
}
}
類似的實現2:
class Solution {
public int hammingWeight(int n) {
int count = 0;
for (int i = 0; i < 32; ++i) {
if ((n & 1) == 1) count++;
n = n >> 1; //不需要使用 >>>
}
return count;
}
}
2018-12-8