[LeetCode] Number Complement

476. Number Complement

The complement of an integer is the integer you get when you flip all the 0‘s to 1‘s and all the 1‘s to 0‘s in its binary representation.

  • For example, The integer 5 is "101" in binary and its complement is "010" which is the integer 2.

Given an integer num, return its complement.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int findComplement(int num) {
long long res = 0, po = 1;
while(num) {
if(num % 2 == 0) res += po;
num /= 2;
po *= 2;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/08/22/PS/LeetCode/number-complement/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.