LEETCODE--Number Complement

来源:互联网 发布:南京seo 编辑:程序博客网 时间:2024/05/16 17:16

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
The given integer is guaranteed to fit within the range of a 32-bit signed integer.
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.
方法一:
刚开始没有好的想法就只好利
异或运算的性质:
使特定位翻转 找一个数,对应X要翻转的各位,该数的对应位为1,其余位为零,此数与X对应位异或即可。
例:X=10101110,使X低4位翻转,用X ^ 0000 1111 = 1010 0001即可。
使相反传的位置范围与相对应范围的全1(1……1)进行异或运算即可得到complement number;
以这个思想的难点就是找到相应的全1数;
法二:
二进制按位计算技巧

class Solution {public:    int findComplement(int num) {        unsigned x = ~0;        while(x & num)            x <<= 1;        return ~x & ~num;    }};
0 0
原创粉丝点击