LeetCode 1009. Complement of Base 10 Integer
考点 | 难度 |
---|---|
Bit Manipulation | Easy |
题目
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 n
, return its complement.
思路
设定fac
为位数(从右向左第一位是1,第二位是2,第三位是4,etc)。先求n
变成二进制之后的最后一位,如果是0就给res
加1*fac
,如果是1就给res加0。
答案
public int bitwiseComplement(int n) {
if(n == 0) return 1; // Checking for base case
int res = 0;
int fac = 1; // keep for 2 basically
while(n != 0){
// first we need to check what is our bit in 2 by taking modulo
res += fac * (n % 2 == 0 ? 1 : 0);
// res is the number convert back to decimal + factor * n % 2 if comes 0 then we take 1 otherwise 0 this is our complement
fac *= 2;
n /= 2;
}
return res;
}