問題(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.
大意:
給出一個(gè)正整數(shù)斋泄,輸出它的補(bǔ)足數(shù)往湿。所謂補(bǔ)足數(shù)是在二進(jìn)制表示上補(bǔ)足。
注意:
1蒲拉、給出的證書保證在32位有符號整型范圍內(nèi)潭苞。
2忽冻、你可以假設(shè)在整數(shù)的二進(jìn)制表示形式中沒有前置0。例1:
輸入:5
輸出:2
解釋:5的二進(jìn)制表示是101(沒有前置0)此疹,它的補(bǔ)足是010僧诚。所以你需要輸出2。例2:
輸入:1
輸出:0
解釋:1的二進(jìn)制表示是1(沒有前置0)秀菱,它的補(bǔ)足是0振诬。所以你需要輸出0。
思路:
題目的意思就是把一個(gè)數(shù)的二進(jìn)制表示中的1和0置換掉衍菱,輸出新的數(shù)字赶么,所以一位位地遍歷原數(shù)字的二進(jìn)制表示,遇到0就在結(jié)果的對應(yīng)比特位上加個(gè)1脊串,這一點(diǎn)可以用左移操作來確定要加1的比特位辫呻,最后直接返回就是答案了。
代碼(C++):
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