Easy
Related Topics: Bit Manipulation
LeetCode Source
十進位數字轉成二進制
之後將1
轉成0
將0
轉成1
結果就是答案
Time Complexity: O(logn)
Space Complexity: O(1)
class Solution:
def findComplement(self, num: int) -> int:
res = ""
for i in range(len(bin(num)[2:])):
if bin(num)[i+2] == "1":
res += "0"
else:
res += "1"
return int(res, 2)
class Solution {
public:
int findComplement(int num) {
string res = "";
string binary = std::bitset<32>(num).to_string();
binary = binary.substr(binary.find('1'));
for (char c : binary) {
if (c == '1') {
res += '0';
} else {
res += '1';
}
}
return std::stoi(res, nullptr, 2);
}
};