476. 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.

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.

算法分析:用一个临时变量t来标记num的二进制数的长度,然后用t-1与num异或,就能得到num的补数。

C语言版

int findComplement(int num) {
    int n = num, t = 1;
    while(n)
    {
        n = n >> 1;
        t = t << 1;
    }

    return num ^ (t - 1);
}

Python版

class Solution(object):
    def findComplement(self, num):
        """
        :type num: int
        :rtype: int
        """
        return num ^ ((1 << num.bit_length()) - 1)

版权声明:本文为Vampirelzl原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。