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