1. 程式人生 > >LintCode 二級制中有多少個1

LintCode 二級制中有多少個1

-- integer one boolean 二進制 dex abs nes tco

public class Solution {
/**
* @param num: an integer
* @return: an integer, the number of ones in num
*/

/*
負數的二進制是其絕對值的補碼(反碼+1)
1 源碼: 0001
1 反碼: 1110
1 補碼: 1111
-1 : 1111
*/
public int countOnes(int num) {
// write your code here
int countZero=0,countOne=0;
int abs=num;
boolean isPlus=true; //正數
if(num<0)
{
abs=Math.abs(num+1);
isPlus=false;

}
int index=32;
while(abs!=0)
{

if((abs%2==1 && isPlus )|| (!isPlus && abs%2==0))
{
countOne++;
}
abs>>=1; //右移1 相當於除2
index--;
}
if(num<0)
countOne+=index; //負數要往前面補一
return countOne;
}

};

LintCode 二級制中有多少個1