
The Fundamental Of Coding Interview Question part 2 (Javascript)
Posted on
Bit Manipulation
- Negative Numbers: 3 => 011, -3 => flip 011 => 100 => 101 => prepend the first bit => 1101
- << && >>> Logical Shift => move every bit to the left/right, the firt/last bit will be cut off, then append/prepend the bits with 0
- >> Arithmetic Right Shift => shift values to the right but fill in the new bits with the value of the sign bit
- get ith bit =>
(num & (1 << i)) != 0 - set ith bit =>
num | 1 << i - clear ith bit =>
let mask = ~(1 << i); return num && mask - clear bits from i to the far right side =>
let mask = (1 << i) - 1; return num && mask - clear bits from i to the far left side =>
let mask = (~0 << i + 1) - 1; return num && mask
tricks learned from questions:
- check number has no 0s(sequence of 0s): n != 0
- check the 2nd digit on the far right side is 0 => n & 2 == 0
Brain Teasers
- checking for prime number => generating a list of primes: time proved way, efficient.
- probability: mutually exclusive and independent can not co-exist if X & Y events have any possibility to happen
- some examples: burn two ropes, nine balls.