476. Number Complement 难度:简单

来源:互联网 发布:淘宝自定义导航条代码 编辑:程序博客网 时间:2024/06/02 07:31

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)
原创粉丝点击