Leetcode 题解
题目链接: 476. 数字的补数
解题思路: 要求补数,由于任何数对于1的异或为本身取反,所以可以用异或性质求解。
题解:
import math
class Solution:
def findComplement(self, num: int) -> int:
if num == 0: return 1
return num ^ ((1 << int(math.log2(num)) + 1) - 1)
Leetcode 题解
题目链接: 476. 数字的补数
解题思路: 要求补数,由于任何数对于1的异或为本身取反,所以可以用异或性质求解。
题解:
import math
class Solution:
def findComplement(self, num: int) -> int:
if num == 0: return 1
return num ^ ((1 << int(math.log2(num)) + 1) - 1)