"""Blind 75, Binary (bit manipulation) section (5 problems)."""
from typing import List

MASK = 0xFFFFFFFF


def get_sum(a: int, b: int) -> int:
    """LC 371. XOR adds without carry, AND<<1 is the carry; repeat. Mask to emulate 32-bit ints in Python."""
    while b & MASK:
        a, b = a ^ b, (a & b) << 1
    a &= MASK
    return a if a <= 0x7FFFFFFF else ~(a ^ MASK)


def hamming_weight(n: int) -> int:
    """LC 191. n & (n - 1) clears the lowest set bit; count how many times until zero."""
    count = 0
    while n:
        n &= n - 1
        count += 1
    return count


def count_bits(n: int) -> List[int]:
    """LC 338. bits(i) = bits(i >> 1) + (i & 1): reuse the answer for i without its last bit."""
    out = [0] * (n + 1)
    for i in range(1, n + 1):
        out[i] = out[i >> 1] + (i & 1)
    return out


def missing_number(nums: List[int]) -> int:
    """LC 268. XOR every index 0..n with every value; pairs cancel and the missing one remains."""
    x = len(nums)
    for i, v in enumerate(nums):
        x ^= i ^ v
    return x


def reverse_bits(n: int) -> int:
    """LC 190. Shift bits out of n from the right and into the result from the left, 32 times."""
    out = 0
    for _ in range(32):
        out = (out << 1) | (n & 1)
        n >>= 1
    return out
