第一种方法:
这个方法比较蠢,就是一个一个的判断,即n>0,和n<0两种情况
然后把二进制码算出来从而求其中1的数量
实例代码:
public
class
Solution {
public
int
NumberOf1(
int
n) {
if
(n==
0
)
return
0
;
int
count=
0
;
if
(n>
0
)
{
while
(n>
0
)
{
if
(n%
2
==
1
) count++;
n/=
2
;
}
}
if
(n<
0
){
String str=Integer.toBinaryString(n); //jdk 中内置的二进制转换函数
char
a[]=str.toCharArray(); //把一个字符串转换为字符数组
for
(
char
a1:a)
{
if
(a1==
'1'
) count++;
}
}
return
count;
}
}
第二种方法,是通过位操作,这种方法虽然简单,但是需要对位操作有着很深的理解
实例代码:
public class Solution {
public int NumberOf1(int n) {
int count = 0;
while (n != 0) {
++count;
n = (n - 1) & n;
}
return count;
}