476数字的补数

476、数字的补数

题目点我

给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。

注意:

给定的整数保证在32位带符号整数的范围内。
你可以假定二进制数不包含前导零位。
示例 1:

输入: 5
输出: 2
解释: 5的二进制表示为101(没有前导零位),其补数为010。所以你需要输出2。
示例 2:

输入: 1
输出: 0
解释: 1的二进制表示为1(没有前导零位),其补数为0。所以你需要输出0。

注意点:

  1. 按照十进制数转二进制的方法来算
  2. 使用异或取反,1^1=0 0^1=1
class Solution {
    public int findComplement(int num) {
        int quotient = num;
        int remainder;
        int ans = 0;
        int count = 0;
        while (quotient != 0) {
            remainder = quotient % 2;
            ans += (remainder ^ 1) * Math.pow(2, count);
            count++;
            quotient /= 2;
        }
        return ans;
    }
}

改进1

  1. 用位运算取二进制的表示,<<相当于×2(有符号),>>>相当于/2(无符号)
class Solution {
    public int findComplement(int num) {
        int remainder;
        int ans = 0;
        int bit = 1;
        while (num != 0) {
            remainder = num & 1;
            ans += (remainder ^ 1) * bit;
            bit = bit << 1;
            num = num >>> 1;
        }
        return ans;
    }
}

改进2

  1. 5的2进制表示为101,补数为010,加起来为111
  2. 所以只要找离目标数最近的111就行,然后用111减去5,得到其补数
  3. Integer.MAX_VALUE = 2147483647 = Math.pow(2, 31) - 1,防止溢出
class Solution {
    public int findComplement(int num) {
        int n=1;
        while(n-num<0&&n<=2147483647){
            n=n*2+1;
        }
        return n-num;
    }
}

猜你喜欢

转载自blog.csdn.net/qq8677/article/details/81071513