Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4bf77a6

Browse files
author
Ram swaroop
committed
power of 2: new method added
1 parent a16a346 commit 4bf77a6

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

src/me/ramswaroop/bits/PowerOf2.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,31 @@ public static boolean isPowerOf2UsingANDoperator(long n) {
3030
return n != 0 && (n & (n - 1)) == 0; // n != 0 check added for input 0
3131
}
3232

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+
3343
public static void main(String a[]) {
3444
System.out.println(isPowerOf2(18));
3545
System.out.println(isPowerOf2UsingANDoperator(18));
46+
System.out.println(isPowerOf2FromRandomClass(18));
3647

3748
System.out.println(isPowerOf2(16));
3849
System.out.println(isPowerOf2UsingANDoperator(16));
50+
System.out.println(isPowerOf2FromRandomClass(16));
3951

4052
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
4255

4356
System.out.println(isPowerOf2(-2)); // doesn't work for -ve no.s
4457
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
4559
}
4660
}

0 commit comments

Comments
 (0)