Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitaa2a87c

Browse files
authored
Create 0201-bitwise-and-of-numbers-range.py
1 parent5171098 commitaa2a87c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# check difference at each bit (cannot be more than left - right)
2+
classSolution:
3+
defrangeBitwiseAnd(self,left:int,right:int)->int:
4+
res=0
5+
6+
foriinrange(32):
7+
bit= (left>>i)&1
8+
ifnotbit:
9+
continue
10+
11+
remain=left% (1<< (i+1))
12+
diff= (1<< (i+1))-remain
13+
ifright-left<diff:
14+
res=res| (1<<i)
15+
returnres
16+
17+
# find the longest matching prefix of set bits between left and right
18+
classSolution:
19+
defrangeBitwiseAnd(self,left:int,right:int)->int:
20+
i=0
21+
whileleft!=right:
22+
left=left>>1
23+
right=right>>1
24+
i+=1
25+
returnleft<<i

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp