-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtil.java
69 lines (64 loc) · 1.55 KB
/
Util.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package algorithm;
public class Util {
/**
* O(logN) time
*
* @param n
* @return
*/
public static boolean isPowerOfTwo_1(int n) {
int tmp = 1;
while (tmp <= n) {
if (tmp == n)
return true;
tmp <<= 1;
}
return false;
}
/**
* O(1) time, bitwise operator
*
* @param n
* @return
*/
public static boolean isPowerOfTwo_2(int n) {
return (n & (n - 1)) == 0;
}
/**
* O(number of ones), bitwise operator
* @param n
* @return
*/
public static int countBinaryOnes(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
++count;
}
return count;
}
public static void main(String[] args) {
System.out.println(isPowerOfTwo_2(0));
System.out.println(isPowerOfTwo_2(1));
System.out.println(isPowerOfTwo_2(2));
System.out.println(isPowerOfTwo_2(3));
System.out.println(isPowerOfTwo_2(4));
System.out.println(isPowerOfTwo_2(6));
System.out.println(isPowerOfTwo_2(7));
System.out.println(isPowerOfTwo_2(8));
System.out.println(isPowerOfTwo_2(9));
System.out.println(isPowerOfTwo_2(1023));
System.out.println(isPowerOfTwo_2(1024));
System.out.println(isPowerOfTwo_2(1025));
System.out.println(countBinaryOnes(0));
System.out.println(countBinaryOnes(1));
System.out.println(countBinaryOnes(2));
System.out.println(countBinaryOnes(3));
System.out.println(countBinaryOnes(6));
System.out.println(countBinaryOnes(7));
System.out.println(countBinaryOnes(8));
System.out.println(countBinaryOnes(1022));
System.out.println(countBinaryOnes(1023));
System.out.println(countBinaryOnes(1024));
}
}