2023年7月15日 星期六

7/15 每日一題(整數的補碼,也就是翻轉2進制,0變1,1變0)

 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 num, return its complement.

 

Example 1:

Input: num = 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.

Example 2:

Input: num = 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.

 

Constraints:

  • 1 <= num < 231







class Solution:
    def findComplement(self, num: int) -> int:
        rev_dict={'0':'1','1':'0'} #將讀到的2進制翻轉
        two_num=bin(num)[2:] #從0b之後開始取值
        res=[] #初始化翻轉list
        for i in two_num:
            res.append(rev_dict[i])
        rev_two_num='0b' + ''.join(res)  #轉成str

        return int(rev_two_num,2)


-----------參考答案

class Solution:
    def findComplement(self, num: int) -> int:
        return (int((bin(n)[2:]).replace('1', '2').replace('0','1').replace('2','0'),2))
            #先把1變成2,0變成1,2再變成0
return (int((bin(n)[2:]).translate(str.maketrans("01", "10")),2))
    #使用str.maketrans()創進一個str映射表,將0映射成1,1映射成0,
    #然後使用translate()根據映射表將二進制字符串中的字符進行轉換
    #最後在使用int(0bXXX,2)轉換成十進制

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁