数的补数 Number Complement

牧云@^-^@ 提交于 2020-04-07 10:52:46

问题:

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.(输出每个数的补码,实际上根据示例是要求实现按位取反)

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Example 1:

Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

解决:

①  注意对输入的数值转换时是32位二进制数,高位为0,不算在计算范围内,应该跳过,从第一个非0数据开始。

class Solution { // 10ms
    public int findComplement(int num) {
        int tmp = (Integer.highestOneBit(num) << 1) - 1; //00..11..1
        num = ~ num;//111...取反之后的值
        return num & tmp;//000...补码
    }
}

进化版:异或的性质---与0相^保留原值,与1相^按位取反,与自身相^结果为0.

public class Solution { // 11ms
    public int findComplement(int num) {
        int mask = (Integer.highestOneBit(num) << 1) - 1;
        return num ^ mask;
    }
}

② 利用异或的性质。

class Solution { // 11ms
    public int findComplement(int num) {
        int tmp = num;
        int count = 0;//记录非0的位数
        while(tmp != 0){
            tmp /= 2;
            count ++;
        }
        return num ^ (int)(Math.pow(2,count) - 1);
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!