-
Notifications
You must be signed in to change notification settings - Fork 70
/
MathUtils.java
executable file
·55 lines (46 loc) · 1.14 KB
/
MathUtils.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
package common;
/**
* Utilities for commonly used math operations.
*/
public class MathUtils {
public static int log2(final int x) {
return (int) (Math.log(x) / Math.log(2));
}
public static long log2(final long x) {
return (long) (Math.log(x) / Math.log(2));
}
public static boolean isPowerOfTwo(final long x) {
return (x & (x - 1)) == 0;
}
public static int lowestPowerOfTwo(final int n) {
if (n < 1) {
return 1;
}
int result = 1;
while (result < n) {
result <<= 1;
}
return result;
}
public static long lowestPowerOfTwo(final long n) {
if (n < 1) {
return 1;
}
long result = 1;
while (result < n) {
result <<= 1;
}
return result;
}
public static int bitreverse(int n, final int bits) {
int count = bits - 1;
int reverse = n;
n >>= 1;
while (n > 0) {
reverse = (reverse << 1) | (n & 1);
n >>= 1;
count--;
}
return ((reverse << count) & ((1 << bits) - 1));
}
}