476. Number Complement

来源:互联网 发布:带着淘宝去异界txt 编辑:程序博客网 时间:2024/06/06 00:14

476.Number Complement

Given apositive integer, output its complement number. The complement strategy is toflip the bits of its binary representation.

Note:

The giveninteger is guaranteed to fit within the range of a 32-bit signed integer.

You couldassume no leading zero bit in the integer’s binary representation.

 

Example1:

Input: 5

Output: 2

Explanation:The binary representation of 5 is 101 (no leading zero bits), and itscomplement is 010. So you need to output 2.

 

Example2:

Input: 1

Output: 0

Explanation:The binary representation of 1 is 1 (no leading zero bits), and its complementis 0. So you need to output 0.

 

输出一个数各位取反之后的数。一开始没考虑直接就 return ~num;

需要注意,一个int在计算机内部是32位,如果直接取反,前面的0000会变成1111,所以在取反的时候要考虑这种情况。参考了别人的思路,很巧妙,利用mask掩码,来回取反,就出来结果了。

class Solution {public:    int findComplement(int num) {        unsigned mask = ~0;        while(mask & num){            mask <<= 1;        }        return ~mask & ~num;    }};

原创粉丝点击