Re: [閒聊] 每日leetcode

看板Marginalman作者 (JerryChung)時間1年前 (2024/08/22 08:29), 編輯推噓1(102)
留言3則, 2人參與, 1年前最新討論串751/1548 (看更多)
https://leetcode.com/problems/number-complement 476. Number Complement 整數的補碼是指將其二進位表示形式中的所有0與1互相翻轉後得到的整數 給一個整數 num 回傳其補碼 Example 1: Input: num = 5 Output: 2 Explanation: 5 的二進位表示為 101 補碼為 010 轉回十進位為 2 Example 2: Input: num = 1 Output: 0 Explanation: 1 的二進位表示為 1 補碼為 0 轉回十進位為 0 Constranints: 1 <= num < 2^31 Python Code: class Solution: def findComplement(self, num: int) -> int: return int(''.join('1' if bit == '0' else '0' for bit in format(num, 'b')), 2) 好不容易有個 Easy 只好來寫一下了 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 60.251.52.67 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1724286557.A.4C4.html

08/22 08:38, 1年前 , 1F
return num ^ (1 << num.bit_length()) - 1
08/22 08:38, 1F

08/22 08:38, 1年前 , 2F
還有這種算法喔
08/22 08:38, 2F

08/22 13:43, 1年前 , 3F
一行解大師
08/22 13:43, 3F
文章代碼(AID): #1cnePTJ4 (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1cnePTJ4 (Marginalman)