File tree Expand file tree Collapse file tree 1 file changed +15
-1
lines changed Expand file tree Collapse file tree 1 file changed +15
-1
lines changed Original file line number Diff line number Diff line change @@ -30,17 +30,31 @@ public static boolean isPowerOf2UsingANDoperator(long n) {
30
30
return n != 0 && (n & (n - 1 )) == 0 ; // n != 0 check added for input 0
31
31
}
32
32
33
+ /**
34
+ * The following code can be found in {@link java.util.Random#nextInt(int)}.
35
+ *
36
+ * @param n
37
+ * @return
38
+ */
39
+ public static boolean isPowerOf2FromRandomClass (long n ) {
40
+ return n != 0 && (n & -n ) == n ;
41
+ }
42
+
33
43
public static void main (String a []) {
34
44
System .out .println (isPowerOf2 (18 ));
35
45
System .out .println (isPowerOf2UsingANDoperator (18 ));
46
+ System .out .println (isPowerOf2FromRandomClass (18 ));
36
47
37
48
System .out .println (isPowerOf2 (16 ));
38
49
System .out .println (isPowerOf2UsingANDoperator (16 ));
50
+ System .out .println (isPowerOf2FromRandomClass (16 ));
39
51
40
52
System .out .println (isPowerOf2 (0 )); // works for 0
41
- System .out .println (isPowerOf2UsingANDoperator (0 )); // works for 0
53
+ System .out .println (isPowerOf2UsingANDoperator (0 )); // works for 0 with a check
54
+ System .out .println (isPowerOf2FromRandomClass (0 )); // works for 0 with a check
42
55
43
56
System .out .println (isPowerOf2 (-2 )); // doesn't work for -ve no.s
44
57
System .out .println (isPowerOf2UsingANDoperator (-2 )); // doesn't work for -ve no.s
58
+ System .out .println (isPowerOf2FromRandomClass (-2 )); // doesn't work for -ve no.s
45
59
}
46
60
}
You can’t perform that action at this time.
0 commit comments