Skip to content

Commit bd86972

Browse files
Bit Manipulation: 201. Bitwise AND of Numbers Range
1 parent e38172b commit bd86972

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package bit_manipulation.medium;
2+
3+
/***
4+
* Problem 201 in Leetcode: https://leetcode.com/problems/bitwise-and-of-numbers-range/
5+
*
6+
* Given two integers left and right that represent the range [left, right],
7+
* return the bitwise AND of all numbers in this range, inclusive.
8+
*
9+
* Example 1:
10+
* Input: left = 5, right = 7
11+
* Output: 4
12+
*
13+
* Example 2:
14+
* Input: left = 0, right = 0
15+
* Output: 0
16+
*
17+
* Example 3:
18+
* Input: left = 1, right = 2147483647
19+
* Output: 0
20+
*/
21+
22+
public class BitwiseAndOfNumbersRange {
23+
public static void main(String[] args) {
24+
int left = 5, right = 2147483647;
25+
26+
System.out.println("Bitwise AND of: " + bitwiseAndOfFrom(left, right));
27+
}
28+
29+
private static int bitwiseAndOfFrom(int left, int right) {
30+
int count = 0;
31+
32+
while (left != right) {
33+
left >>= 1;
34+
right >>= 1;
35+
count++;
36+
}
37+
38+
return left << count;
39+
}
40+
}

0 commit comments

Comments
 (0)