1 min read
277 words
Problem Statement
leetcode problem link
Solution [accepted]
class Solution:
def findComplement(self, num: int) -> int:
res = num
mask = 1
while num > 0:
res = res ^ mask
mask <<= 1
num >>= 1
return res
public class Solution {
public int FindComplement(int num) {
int res = num;
int temp = num;
int mask = 1;
while (temp > 0) {
res ^= mask;
mask <<= 1;
temp >>= 1;
}
return res;
}
}
Editorial
Approach 1: Flip Bit by Bit
class Solution:
def findComplement(self, num):
todo, bit = num, 1
while todo:
# flip the current bit
num = num ^ bit
# prepare for the next run
bit = bit << 1
todo = todo >> 1
return num
Leave a comment