ビット演算バイナリの1の個数
タイトル
タイトルリンク:バイナリの1つの数
問題解
10進法で2進法に変換して先に型を外してください.負数の場合、その絶対値の補符号を出力する必要があります.負数が発生した場合、その数字を負数として記録し、絶対値をとる.バイナリを遍歴し,そのビットが1であるか0であるかを判断し,記録する.この数字が負数であれば32-0の個数を出力し、そうでなければ1の個数を出力する(直接bitCountであってもよい).
ACコード
方法1
方法2
方法3
タイトルリンク:バイナリの1つの数
問題解
10進法で2進法に変換して先に型を外してください.負数の場合、その絶対値の補符号を出力する必要があります.負数が発生した場合、その数字を負数として記録し、絶対値をとる.バイナリを遍歴し,そのビットが1であるか0であるかを判断し,記録する.この数字が負数であれば32-0の個数を出力し、そうでなければ1の個数を出力する(直接bitCountであってもよい).
ACコード
方法1
class Solution {
public:
int NumberOf1(int n) {
bool flag = false;
if (n < 0) {
flag = true;
n = -n;
}
int z = 0, o = 0;
while (n != 0) {
int t = n % 2;
if (t==0) z++;
else o++;
n /= 2;
}
return flag ? (32 - z) : o;
}
};
方法2
class Solution {
public:
int NumberOf1(int n) {
int cnt = 0;
while (n) {
n &= (n-1);
cnt++;
}
return cnt;
}
};
方法3
class Solution {
public int NumberOf1(int n)
{
return Integer.bitCount(n);
}
}