給一個整數,回傳一個bit位互補(即 OR 後的 bit 每一位都是1)的數。
(這題跟 1009 Complement of Base 10 Integer 是相同的,只是換了名)
這題的邏輯很簡單,找出一個與 num 相同 bit 位長度且每一位都是 1 的數,再用 XOR 去求解。
為了必避免C#的int溢位,所以使用推進的方式,而不是由高位減一。
Python
class Solution:
def findComplement(self, num: int) -> int:
return ((1 << num.bit_length()) - 1 ) ^ num
C#
public class Solution {
public int FindComplement(int num) {
int r = 1;
while(r < num)
{r = (r << 1) + 1;}
return r ^ num;
}
}