问题(Easy):
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.
大意:
给出一个正整数,输出它的补足数。所谓补足数是在二进制表示上补足。 注意: 1、给出的证书保证在32位有符号整型范围内。 2、你可以假设在整数的二进制表示形式中没有前置0。 例1: 输入:5 输出:2 解释:5的二进制表示是101(没有前置0),它的补足是010。所以你需要输出2。 例2: 输入:1 输出:0 解释:1的二进制表示是1(没有前置0),它的补足是0。所以你需要输出0。
思路:
题目的意思就是把一个数的二进制表示中的1和0置换掉,输出新的数字,所以一位位地遍历原数字的二进制表示,遇到0就在结果的对应比特位上加个1,这一点可以用左移操作来确定要加1的比特位,最后直接返回就是答案了。
代码(C ):
代码语言:javascript复制class Solution {
public:
int findComplement(int num) {
int res = 0;
int bit = 1;
while (num > 0) {
int temp = num % 2;
if (temp == 0) res = res bit;
num = num / 2;
bit = bit << 1;
}
return res;
}
};
合集:https://github.com/Cloudox/LeetCode-Record