- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBitManipulation.java
More file actions
Latest commit
38 lines (31 loc) · 865 Bytes
/
Copy pathBitManipulation.java
File metadata and controls
38 lines (31 loc) · 865 Bytes
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
/**
* Fundamental bit manipulation operations you must know Time Complexity: O(1)
*
* @author Micah Stairs
*/
publicclassBitManipulation {
// Sets the i'th bit to 1
publicstaticintsetBit(intset, inti) {
returnset | (1 << i);
}
// Checks if the i'th is set
publicstaticbooleanisSet(intset, inti) {
return (set & (1 << i)) != 0;
}
// Sets the i'th bit to zero
publicstaticintclearBit(intset, inti) {
returnset & ~(1 << i);
}
// Toggles the i'th bit from 0 -> 1 or 1 -> 0
publicstaticinttoggleBit(intset, inti) {
returnset ^ (1 << i);
}
// Returns a number with the first n bits set to 1
publicstaticintsetAll(intn) {
return (1 << n) - 1;
}
// Verifies if a number n is a power of two
publicstaticbooleanisPowerOfTwo(intn) {
returnn > 0 && (n & (n - 1)) == 0;
}
}