Skip to content

Bit Basics

Table of Contents

3370. Smallest Number With All Set Bits

3226. Number of Bit Changes to Make Two Integers Equal

1356. Sort Integers by The Number of 1 Bits

461. Hamming Distance

2220. Minimum Bit Flips to Convert Number

476. Number Complement

1009. Complement of Base 10 Integer

868. Binary Gap

3211. Generate Binary Strings Without Adjacent Zeros

2917. Find the K-or of an Array

693. Binary Number with Alternating Bits

2657. Find the Prefix Common Array of Two Arrays

231. Power of Two

342. Power of Four

191. Number of 1 Bits

191. Number of 1 Bits - Python Solution
# Bit Manipulation
def hammingWeight1(n: int) -> int:
    res = 0

    while n != 0:
        n = n & (n - 1)  # Unset the rightmost 1-bit
        res += 1

    return res


def hammingWeight2(n: int) -> int:
    return bin(n).count("1")


def hammingWeight3(n: int) -> int:
    def decimalToBinary(n: int) -> str:
        if n == 0:
            return "0"

        binary = ""
        while n > 0:
            binary = str(n % 2) + binary
            n //= 2

        return binary

    binary = decimalToBinary(n)

    return binary.count("1")


n = 11
print(hammingWeight1(n))  # 3
print(hammingWeight2(n))  # 3

n = 47
print(bin(n))

2595. Number of Even and Odd Bits

  • LeetCode | LeetCode CH (Easy)

  • Tags: bit manipulation

  • Topic: Bit Manipulation
  • Difficulty: Easy

You are given a positive integer n. Let even denote the number of even indices in the binary representation of n with value 1. Let odd denote the number of odd indices in the binary representation of n with value 1. Note that bits are indexed from right to left in the binary representation of a number. Return the array [even, odd].

338. Counting Bits

338. Counting Bits - Python Solution
from typing import List


# Bit Manipulation
def countBits(n: int) -> List[int]:
    bits = [0 for _ in range(n + 1)]

    for i in range(1, n + 1):
        bits[i] = bits[i >> 1] + (i & 1)

    return bits


n = 5
print(countBits(n))  # [0, 1, 1, 2, 1, 2]

Comments