剑指offer第十题,直接的反应是通过右移在和1与,但是发现这个方法在输入负数的时候有问题,会进入死循环,因此想到用左移
package com.zjy.sword2offer;
public class NumberOf1 {
public static int Number(int n){
int flag = 1;
int count = 0;
while(flag!=0)
{
if((n&flag)!=0)//不能用(n&flag)==0,只能保证大于0,但是不是等于1
count++;
flag = flag<<1;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int res = Number(8);
System.out.println(res);
boolean b = (8&8)==1;
System.out.println(b);
}
}