1009. Complement of Base 10 Integer: 10的補數
1009. Complement of Base 10 Integer: 10的補數
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
5is"101"in binary and its complement is"010"which is the integer2.
Given an integer n, return its complement.
讓你算10的補數
我觀察了一下
發現就是找第一個s 使得 2**s-1>=n 然後用2**s-n-1即可
參考底下的python code:
class Solution: def bitwiseComplement(self, n: int) -> int: if n==0 or n==1: return 1-n s=1 while True: s=2*s if s-1>=n: return s-1-n
留言
張貼留言