The number of digital complement

Given a positive integer, output its complement. Complement is a negation of the binary number.

note:

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

Example 1:

Input: 5
Output: 2
Explanation: 5 is represented by binary 101 (no leading zero bits), which is the complement of 010. So you need to output 2.

Example 2:

Input: 1
Output: 0
Explanation: 1 is represented by a binary 1 (no leading zero bits), which complement is 0. So you need to output 0.

class Solution {
    public int findComplement(int num) {
        if(num > Integer.MAX_VALUE / 2){//大于MAX_VALUE的一半时,位数已经与MAX_VALUE一样,可以用MAX_VALUE异或
            return num ^ Integer.MAX_VALUE;
        }
        
        //拿到刚好比num大的2的倍数
        int i = 1;
        while(i <= num){
            i = i * 2;
        }
        
        //拿到的数,减一刚好是与num位置相等的所有二进制为1的数
        i -= 1;
        
        return i ^ num;
    }
    
//     8           1000    |     5       101
//     16         10000    |     8      1000
//     15          1111    |     7       111
        
//     8 ^ 15      0111    |     5 ^ 7   010
    
}

Guess you like

Origin blog.csdn.net/weixin_33885676/article/details/90847416