File tree 1 file changed +40
-0
lines changed
src/bit_manipulation/medium
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments