File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package me .ramswaroop .bits ;
2
+
3
+ /**
4
+ * Created by ramswaroop on 30/05/2016.
5
+ */
6
+ public class BinaryGap {
7
+
8
+ /**
9
+ * A binary gap of a positive integer N is any maximal
10
+ * sequence of consecutive zeros that is surrounded by ones
11
+ * at both ends in the binary representation of N.
12
+ *
13
+ * @param n
14
+ * @return
15
+ */
16
+ public static int findBinaryGap (long n ) {
17
+ int gap = 0 ;
18
+ int maxGap = 0 ;
19
+ while (n > 0 ) {
20
+ if ((n & 1 ) == 1 ) {
21
+ n = n >>> 1 ;
22
+ while (n > 0 && (n & 1 ) == 0 ) {
23
+ gap ++;
24
+ n = n >>> 1 ;
25
+ }
26
+ if (gap > maxGap ) {
27
+ maxGap = gap ;
28
+ gap = 0 ;
29
+ }
30
+ }
31
+ n = n >>> 1 ;
32
+ }
33
+
34
+ return maxGap ;
35
+ }
36
+
37
+ public static int findMaxNoOf0sBetweenTwo1s (long n ) {
38
+ return findBinaryGap (n );
39
+ }
40
+
41
+ public static void main (String [] args ) {
42
+ System .out .println (findBinaryGap (2 ));
43
+ System .out .println (findBinaryGap (8 ));
44
+ System .out .println (findBinaryGap (9 ));
45
+ System .out .println (findBinaryGap (16 ));
46
+ System .out .println (findBinaryGap (17 ));
47
+ System .out .println (findMaxNoOf0sBetweenTwo1s (121 ));
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments