Skip to content

Commit f934b52

Browse files
committed
Add chapter 18 - Bit manipulation
* Hamming Weights Of Integers * Lonely Integer * Swap Odd And Even Bits
1 parent 8e052dc commit f934b52

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
fun hammingWeightsOfIntegers(n: Int): List<Int> {
2+
return (1..n).map { countSetBits(it) }
3+
}
4+
5+
fun countSetBits(n: Int): Int {
6+
var x = n
7+
var count = 0
8+
// Count each set bit of 'x' until 'x' equals 0.
9+
while (x > 0) {
10+
// Increment the count if the LSB is 1.
11+
count += x.and(1)
12+
// Right shift 'x' to shift the next bit to the LSB position.
13+
x = x.shr(1)
14+
}
15+
return count
16+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fun hammingWeightsOfIntegersDp(n: Int): List<Int> {
2+
// Base case: the number of set bits in 0 is just 0. We set dp[0] to
3+
// 0 by initializing the entire DP array to 0.
4+
val dp = IntArray(n + 1)
5+
for (x in 1..n) {
6+
// 'dp[x]' is obtained using the result of 'dp[x >> 1]', plus
7+
// the LSB of 'x'.
8+
dp[x] = dp[x ushr 1] + (x and 1)
9+
}
10+
return dp.toList()
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fun lonelyInteger(nums: List<Int>): Int {
2+
var res = 0
3+
// XOR each element of the array so that duplicate values will
4+
// cancel each other out (x ^ x == 0).
5+
for (n in nums) {
6+
res = res.xor(n)
7+
}
8+
// 'res' will store the lonely integer because it would not have
9+
// been canceled out by any duplicate.
10+
return res
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fun swapOddAndEvenBits(n: Long): Long {
2+
val evenMask: Long = 0x55555555 // 01010101010101010101010101010101
3+
val oddMask: Long = 0xAAAAAAAA // 10101010101010101010101010101010
4+
val evenBits = n.toLong() and evenMask
5+
val oddBits = n.toLong() and oddMask
6+
// Shift the even bits to the left, the odd bits to the right, and
7+
// merge these shifted values together.
8+
// shl - signed shift left
9+
// ushr - unsigned shift right
10+
return (evenBits shl 1) or (oddBits ushr 1)
11+
}

0 commit comments

Comments
 (0)