Re: [閒聊] 每日LeetCode

看板Marginalman作者 (leaf)時間3月前 (2024/02/21 22:21), 3月前編輯推噓0(000)
留言0則, 0人參與, 最新討論串704/719 (看更多)
※ 引述《SecondRun (南爹摳打)》之銘言: : 201. Bitwise AND of Numbers Range : 給你left跟right兩個整數 : 回傳left AND left+1 AND left+2 AND ... AND right : C# code: : public class Solution { : public int RangeBitwiseAnd(int left, int right) { : while(right > left) right &= right-1; : return right; : } : } 我的思路是逐個檢查位, 只要左右兩端點都為1的位, 且兩端點的差距不大於該位的值, 該位的值就一定包含在答案中 Python Code: class Solution: def rangeBitwiseAnd(self, left: int, right: int) -> int: ans = 0 i = 0 while left >= 2**i or right >= 2**i: if left & 2**i and right & 2**i and right - left < 2**i: ans += 2**i i += 1 return ans -- C++ Code: class Solution { public: int rangeBitwiseAnd(int left, int right) { int ans = 0; long i = 1; while (left >= i || right >= i) { if ((left & i) > 0 && (right & i) > 0 && right - left < i) ans += i; i <<= 1; } return ans; } }; -- 咖啡是一種豆漿, 茶是一種蔬菜湯。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.163.144.190 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1708525260.A.613.html ※ 編輯: leafff (1.163.144.190 臺灣), 02/21/2024 22:22:08
文章代碼(AID): #1brWRCOJ (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1brWRCOJ (Marginalman)