| Problem Names | Solution Writeups | Code |
|---|---|---|
| Single Number |
Since the question gurantees that there is only one number that does not have its duplicates, the rest of the numbers all repeated twice. And we know that a XOR a = 0, so if we XOR all the numbers in the array, we will finally obtain that single number. |
|
| Number of 1 Bits |
The input is fixed length of 32. Create a mask initially = 1, and then keep left shift by 1 to check each position contains 1 or 0. |
|
| Counting Bits |
For each number generated, count how many 1 it holds. Record te result in an array. |
|
| Reverse Bits |
Since input is a fixed size 32 bits integer, the way to reverse is that we check from rightmost everytime if that digit holds 1, ans += 1 << (31 - i), where i is the bit position. |
|
| Missing Number |
One simple approach is that we first calculate cumulative sum of n, then for each number in the array, sum -= num. In the end sum will store the only missing number. Another approach of bit manipulation is that we first calculate the result after XOR all the numbers from 0 to n. Then in the given array, we again XOR result with num, and eventually we will get the only missing number. |
|
| Sum of Two Integers |
Loop while b is not 0, Sum bit = a XOR b, carry bit = (unsigned int)(a&b)<<i, since when both digits contain 1, carry = 1. Then update a to sum_bit and b to carry. |
|
| Reverse Integer |
Non-bit-manipulation approach is to push each digit to stack, and when popping from stack, times 10 to its corresponding power to the digit. |