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 5 is "101" in binary and its complement is "010" which is the integer 2.

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

留言

這個網誌中的熱門文章

1041. Robot Bounded In Circle 機器人在圈圈裏面?

382. Linked List Random Node: 隨機選元素從list裡面

2134. Minimum Swaps to Group All 1's Together II 使得所有1連在一起