Bit Manipulation

Bit Manipulation

  • Basic operation
  • Basic use case
  • Interview Questions

How Integer is stored in Memory

Integer -> 4 bytes -> 32 bits

Long -> 8 bytes -> 64 bits

Boolean/Char -> 1 byte

 

Two's complement

Basic Operation

  • Bitwise NOT
    • ~0111 = 1000
  • Bitwise OR
    • 0101 | 1010 = 1111
  • Bitwise AND
    • 0101 & 1100 = 0100
  • Bitwise XOR
    • 0101 ^ 0011 = 0110

Basic Operation

 

  • Bitwise SHIFT
    • 0001 << 3 = 1000
    • 1100 >> 1 = 1110  -- arithmetic
    • 1100 >>> 1 = 0110  -- logical

Basic use case (Tricks)

  • Even & Odd
    • n & 1 == 1 ? Odd : Even
  • Double
    • a / 2 = a >> 1;
    • a * (2^m) = a << m;
  • Negative number
    • a  = 101101100
    • -a = 010010011 + 1 = 010010100
    • Bit NOT on every bit and then plus 1.

Basic use case (Tricks)

  • Specific bit operation
    • Get kth bit:     (a >> k) & 1
    • Set kth bit 0:  a = a & ~(1 << k)
    • Set kth bit 1:  a = a | (1 << k)

Basic use case (Tricks)

  • XOR
    • a ^ a = 0
    • a ^ 0 = a

Interview Questions

  • Bit operation
    • Single Number
    • Number of 1 Bits
    • Reverse Bits
  • Reduce storage & improve efficiency
    • Combination

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

public int singleNumber(int[] A) {
    for (int i = 1; i < A.length; i++) {
        A[i] ^= A[i-1];
    }
    return A[A.length-1];
}

Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

    def singleNumber(self, A: List[int]) -> int:
        for i in range(1, len(A)):
            A[i] ^= A[i-1]
        return A[-1]

Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has. (also known as the Hamming weight)

public int hammingWeight(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) {
        result += n & 1;
        n >>= 1;
    }
    return result;
}

Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of ’1' bits it has. (also known as the Hamming weight)

    def hammingWeight(self, n: int) -> int:
        result = 0
        for i in range(32):
            result += n & 1
            n >>= 1
        return result

Copy of [GoValley-Jo] Bit Manipulation 12

By ZhiTongGuiGu

Copy of [GoValley-Jo] Bit Manipulation 12

  • 7