476 Number Complement Number's complement

Given a positive integer, output its complement. Complement is the inversion of the binary representation of the number.
Note:
    The given integer is guaranteed to be within the range of a 32-bit signed integer.
    You can assume that binary numbers do not contain leading zeros.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (without leading zeros) 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 (without leading zeros) and its complement is 0. So you need to output 0.
See: https://leetcode.com/problems/number-complement/description/

C++:

class Solution {
public:
    int findComplement(int num) {
        bool start=false;
        for(int i=31;i>=0;--i)
        {
            if(num&(1<<i))
            {
                start=true;
            }
            if(start)
            {
                num^=(1<<i);
            }
        }
        return num;
    }
};

 Reference: http://www.cnblogs.com/grandyang/p/6275742.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324600035&siteId=291194637