"""Stage 17: Bit Manipulation and Math (problems 148-150)."""
from __future__ import annotations

from typing import List


def single_number(nums: List[int]) -> int:
    """LC 136. x ^ x = 0 and x ^ 0 = x, so XOR of everything leaves the single value."""
    out = 0
    for x in nums:
        out ^= x
    return out


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


def rotate(matrix: List[List[int]]) -> None:
    """LC 48. Rotate 90 degrees clockwise in place = transpose, then reverse each row."""
    n = len(matrix)
    for r in range(n):
        for c in range(r + 1, n):
            matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
    for row in matrix:
        row.reverse()
