Re: [閒聊] 每日leetcode

作者: JerryChungYC (JerryChung)   2024-08-22 08:29:15
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 只好來寫一下了
作者: JerryChungYC (JerryChung)   2024-08-22 08:38:00
return num ^ (1 << num.bit_length()) - 1還有這種算法喔

Links booklink

Contact Us: admin [ a t ] ucptt.com