EPI - Bits Manipulation
Counting Bits
do until x & (x - 1) > 0
Multiplication of two integers a x b without arithmetical operators
ret = 0 count = 0 while b > 0: if b & 0x1 == 1: ret = ret | (a << count) count += 1 b >>= 1 return ret
Reverse digit
% and /
Convert a number to hexadecimal
- 4 bits & 0xf - add to a [] from right to left
Check if a decimal integer is a palindrome
- BF: convert to string and compare => O(n) space - Trivial => do it until 2 numbers from MSB & LSB are equal - Non-Trivial: numDigits = math.floor(log10(x)) + 1. MSB = x/10^n, LSB: x/10
compute a / b using only the addition, subtraction, and shifting operators
- Brute Force: a - b - b ... until remainder < b - (2^k) x b < a
Generate uniform number
- iterate from 0 to k-th bit (2^k) - [a, b] -> [0, b - a], b - a ~ 2^k
compute x^y x: double y: int
- x^5 = x^2 . x^2 . x - x^(101) vs x^(100) - when y negative => y = -1 and x = 1/x
Find closet integer with same weight
1. Find bit 1 at lsb 2. Find bit 0 at msb 3. Throws exception if all bits are 0 / 1
Reverse Bits
abcdefgh => efgh-abcd => gh-ef-cd-ab => hgfedcba
Binary watch Given a non-negative integer n which represents the number of LEDs that are currently on, return all possible times the watch could represent.
binary watch
Sum of two integers
int Add(int x, int y) { // Iterate till there is no carry while (y != 0) { // carry now contains common set bits of x and y int carry = x & y; // Sum of bits of x and y where at least one of the bits is not set x = x ^ y; // Carry is shifted by one so that adding it to x gives the required sum y = carry << 1; } return x; }
Substract of two integer
int subtract(int x, int y) { // Iterate till there is no carry while (y != 0) { // borrow contains common set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x and y where at least // one of the bits is not set x = x ^ y; // Borrow is shifted by one so that subtracting it from // x gives the required sum y = borrow << 1; } return x; }
Rectangle intersection
left = min(l1, l2) right = max(r1, r2) top = max(t1, t2) bottom = min(b1, b2) check if left < right and bottom < top:
Checking if it's power of four
not x & (x - 1) and x & 0x55555555
Find the difference between 2 strings Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
use bit
Single Number 1 Given an array of integers, every element appears twice except for one. Find that single one.
xor