Re: [閒聊] 每日LeetCode

作者: leafff (LEAF)   2024-02-21 22:20:57
※ 引述《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

Links booklink

Contact Us: admin [ a t ] ucptt.com