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

Commit5171098

Browse files
authored
Create 0201-bitwise-and-of-numbers-range.kt
1 parent9e6da5d commit5171098

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// check difference at each bit (cannot be more than left - right)
2+
classSolution {
3+
funrangeBitwiseAnd(left:Int,right:Int):Int {
4+
var res=0
5+
6+
for (iin0 until32) {
7+
val bit= (left shr i)and1
8+
if (bit==0)continue
9+
10+
val remain= left% (1 shl (i+1))
11+
val diff= (1 shl (i+1))- remain
12+
if (right- left< diff)
13+
res= resor (1 shl i)
14+
}
15+
16+
return res
17+
}
18+
}
19+
20+
// find the longest matching prefix of set bits between left and right
21+
classSolution {
22+
funrangeBitwiseAnd(left:Int,right:Int):Int {
23+
var i=0
24+
var left= left
25+
var right= right
26+
27+
while (left!= right) {
28+
left= left shr1
29+
right= right shr1
30+
i++
31+
}
32+
33+
return left shl i
34+
}
35+
}
36+
37+
// find the longest matching prefix of set bits between left and right. As above but a little different logically.
38+
classSolution {
39+
funrangeBitwiseAnd(left:Int,right:Int):Int {
40+
var right= right
41+
42+
while (right> left) {
43+
right= rightand (right-1)
44+
}
45+
46+
return right
47+
}
48+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp