題目描述:
請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù)胧华,輸入一個(gè)整數(shù),輸出該數(shù)二進(jìn)制表示中 1 的個(gè)數(shù)介却。例如柱搜,把 9 表示成二進(jìn)制是 1001,有 2 位是 1癣蟋。因此透硝,如果輸入 9,則該函數(shù)輸出 2疯搅。
示例 1:
輸入:00000000000000000000000000001011
輸出:3
解釋:輸入的二進(jìn)制串 00000000000000000000000000001011 中濒生,共有三位為 '1'。
示例 2:
輸入:00000000000000000000000010000000
輸出:1
解釋:輸入的二進(jìn)制串 00000000000000000000000010000000 中幔欧,共有一位為 '1'罪治。
示例 3:
輸入:11111111111111111111111111111101
輸出:31
解釋:輸入的二進(jìn)制串 11111111111111111111111111111101 中,共有 31 位為 '1'礁蔗。
注意(負(fù)數(shù)問題):
1觉义、由題意可知,n的十進(jìn)制數(shù)可能為正數(shù)也有可能是負(fù)數(shù)(負(fù)數(shù)二進(jìn)制最高位為1)浴井,
因此可以采用無符號(hào)右移晒骇,空位補(bǔ)0,n為負(fù)數(shù)時(shí)不能補(bǔ)1磺浙。
Java解法一(無符號(hào)右移):
思路:
判斷最低位是否為1洪囤,如果為1計(jì)數(shù)一次。無符號(hào)位右移一次撕氧,繼續(xù)重復(fù)改操作直到該數(shù)變?yōu)?終止循環(huán)瘤缩;
代碼實(shí)現(xiàn):
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int res = 0;
while(n != 0){
res += n & 1;
n = n>>>1;
}
return res;
}
}
和1按位與運(yùn)算,按位與運(yùn)算&伦泥,兩個(gè)整型數(shù)據(jù)對(duì)應(yīng)為為1剥啤,結(jié)果對(duì)應(yīng)位為1何暮,否則對(duì)應(yīng)為0。
例如:
1111 0011 & 0000 0001 結(jié)果:0000 0001
1111 0010 & 0000 0001 結(jié)果:0000 0000
java中右移">>"和無符號(hào)右移">>>"的區(qū)分:
無符號(hào)右移:最高位為0或?yàn)?铐殃,右移空位都填0海洼。
右移:最高位為0,右移空位填0富腊;最高位為1右移空位填1坏逢。
注意:最高位為符號(hào)位。
Java解法二(左移):
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
int flag = 1;
int i = 0;
while(i < 32){
if ((n & flag) != 0)
{
count++;
}
flag = flag << 1;
i++;
}
return count;
}
}
左移方法需要注意:
1赘被、整數(shù)的存儲(chǔ)包括符號(hào)位(1位)與數(shù)值位(n-1)位是整。符號(hào)位為0或者1,0代表正整數(shù)民假,1代表為負(fù)數(shù)浮入。數(shù)值位根據(jù)數(shù)據(jù)類型來確定多少位。在JAVA中整數(shù)類型有四種:type(8位) short(16位) int(32位) long(64位)羊异。所以他們對(duì)應(yīng)的數(shù)值位分別為7事秀,15,31野舶,63位易迹。
2、由于本題數(shù)值是整型平道,也就是32位睹欲,因此需要循環(huán)32次。
Java解法三(巧用 n & (n - 1)):
算法流程:
初始化數(shù)量統(tǒng)計(jì)變量 count 一屋。
循環(huán)消去最右邊的 1 :當(dāng) n = 0時(shí)跳出窘疮。
count += 1 : 統(tǒng)計(jì)變量加 1 ;
n &= n - 1 : 消去數(shù)字 n 最右邊的 1 冀墨。
返回統(tǒng)計(jì)數(shù)量 count 闸衫。
代碼實(shí)現(xiàn):
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int count = 0;
while(n != 0)
{
count++;
n &= n-1;
}
return count;
}
}
解釋:
(n?1) 解析: 二進(jìn)制數(shù)字 n 最右邊的 1 變成 0 ,此 1 右邊的 0 都變成 11 轧苫。
n & (n - 1)解析: 二進(jìn)制數(shù)字 n 最右邊的 1 變成 0 楚堤,其余不變疫蔓。
每次消去一個(gè)1.png
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof