问题:https://leetcode.com/problems/number-complement/?tab=Description
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.
给定给一个正整数,输出其补码,补码的策略是按位取反。
注:
1.给定的数的范围在32位有符号整数。
2.假设没有前导0,即5的二进制就是101。
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.
分析:从最高位的1开始向后按位取反。左移运算符(<<),左移运算将一个位串信息向左移指定的位,右端空出的位用0补充。在二进制数运算中,在信息没有因移动而丢失的情况下,每左移1位相当于乘2。如4 << 2,结果为16。右移运算符(>>),右移运算将一个位串信息向右移指定的位,右端移出的位的信息被丢弃。与左移相反,对于小整数,每右移1位,相当于除以2。按位异或运算符(^),按位异或运算将两个运算分量的对应位按位遵照以下规则进行计算: 0 ^ 0 = 0, 0 ^ 1 = 1, 1 ^ 0 = 1, 1 ^ 1 = 0。即相应位的值相同的,结果为 0,不相同的结果为 1。例如,013^035结果为026。异或运算的意思是求两个运算分量相应位值是否相异,相异的为1,相同的为0。按位异或运算的典型用法是求一个位串信息的某几位信息的反。如欲求整型变量j的最右4位信息的反,用逻辑异或运算017^j,就能求得j最右4位的信息的反,即原来为1的位,结果是0,原来为0的位,结果是1。
参考C++代码:
class Solution {
public:
int findComplement(int num) {
int tem=num;
int cou=1;
while(tem!=0){
tem=tem>>1;
cou=cou<<1;
}
return (cou-1) ^ num;
}
};