正负数的原码与补码

一、介绍

负数的原码就是在最左边的符号位置 1 ,其他各位与其绝对值无异。

负数的补码就是其原码的按位取反再加 1 。

//求一个整数(可以为负)的二进制表示中'1'的个数
public int getNumOf1(int n){
    char[] ch = Integer.toBinary(n).toCharArray();
    int sum = 0;
    for(char c : ch){
        if(c=='1')
            sum++;
    }
    return sum;
}

或者

public static int getNumberOfN2(int n){
    int sum = 0;
    while(n!=0){
        sum++;
        n = n&(n-1);
    }
    return sum;
}

或者

public static int getNumberOfN3(int n){
    return Integer.toBinaryString(n).replaceAll("0", "").length();
}

 

posted @ 2017-08-24 17:33  zhengmengen  阅读(755)  评论(0编辑  收藏  举报