剑指 Offer 15. 二进制中1的个数
请实现一个函数,输入一个整数(以二进制串形式),输出该数二进制表示中 1 的个数。例如,把 9 表示成二进制是 1001,有 2 位是 1。因此,如果输入 9,则该函数输出 2。
示例 1:
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
示例 2:
输入:00000000000000000000000010000000
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。
示例 3:
输入:11111111111111111111111111111101
输出:31
解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。
提示:
输入必须是长度为32的二进制串。
v1
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int c = 0;
for(int i = 0; i < 32; ++i){
if(n % 10 == 1){
++c;
}
n = (int)(n / 10);
}
return c;
}
}
这是我的第一版,既然题目给的是32位的数,那每次取个位数不就好了,然而提交错误了,我想不明白为什么,于是直接输出n看它给的是什么值,好家伙,原来不是二进制串,而是十进制数,于是我对代码进行了修改。
v2
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int c = 0;
for(int i = 0; i < 32; ++i){
if(n % 2 == 1){
++c;
}
n = (int)(n / 2);
}
return c;
}
}
我心想这样总该可以了吧,然而还是错的,因为对于负数的二进制数是补码形式的,唉,于是改成了这样
v3
public class Solution {
// you need to treat n as an unsigned value
public int hammingWeight(int n) {
int c = 0;
boolean f = true;
boolean jo = true;
if(n < 0){
n = -n;
f = false;
if(n % 2 == 0){
jo = true;
}else{
jo = false;
}
}
for(int i = 0; i < 32; ++i){
if(n % 2 == 1){
++c;
}
n = (int)(n / 2);
}
int a = 0;
if(jo){
a = 32 -c;
}else{
a = 33 - c;
}
return f ? c : a;
}
}
啊,还是错的。。。
v4
最后还是我想复杂了,没有想到相与运算。。
public class Solution {
public int hammingWeight(int n) {
int res = 0;
while(n != 0) {
res += n & 1;
n >>>= 1;
}
return res;
}
}