题目:
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.
翻译:
给定一个正数,输出它的补数。补数的策略是翻转其二进制表示的位。
注意:
- 给定的数字保证是符合32-位有符号数的范围。
- 你可以假设在数字的二进制表示前面没有前置零位。
例子1:
输入: 5 输出: 2 解释: 5的二进制表示是101(没有前置零位),并且它的补数为010.所以你需要输出2。
例子2:
输入: 1 输出: 0 解释: 1的二进制表示为1(没有前置零位),并且它的补数为0,所以你需要输出0。
思路:
主要需要考虑的是没有前置零的问题,因此,我们先得到0的补数mask,然后通过和给定的数字num比较,将除了前置零位的mask的其他位都置为0,最后用num的补数和mask进行异或。
C++代码(Visual Studio 2017):
#include "stdafx.h"
#include <iostream>
using namespace std;
class Solution {
public:
int findComplement(int num) {
unsigned mask = ~0;
while (num&mask)
mask <<= 1;
return ~num^mask;
}
};
int main()
{
Solution s;
int num = 5;
int result;
result = s.findComplement(num);
cout << result;
return 0;
}