Number Complement

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.

题意:给你一个正数,将其转换成各个位与之相反的数。

思路:我们可以找一个有效位和所给的数相同,且每一位都是1的数与之做异或运算,即可得到答案。

/**
     * 
     * @Title: findComplement 
     * @Description: Number Complement 
     * @Example :
        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.
     */
    public int findComplement(int num) {
        int xorNum = 1;
        int n = num >> 1;
        while(n > 0){
            xorNum = ((xorNum << 1) + 1);
            n = n >> 1;
        }
        return num ^ xorNum;
    }

需要注意的是位运算的优先级低于+运算,因此加了括号。

原文地址:https://www.cnblogs.com/insaneXs/p/6371114.html