Bit Basics¶
Table of Contents¶
- 3370. Smallest Number With All Set Bits (Easy)
- 3226. Number of Bit Changes to Make Two Integers Equal (Easy)
- 1356. Sort Integers by The Number of 1 Bits (Easy)
- 461. Hamming Distance (Easy)
- 2220. Minimum Bit Flips to Convert Number (Easy)
- 476. Number Complement (Easy)
- 1009. Complement of Base 10 Integer (Easy)
- 868. Binary Gap (Easy)
- 3211. Generate Binary Strings Without Adjacent Zeros (Medium)
- 2917. Find the K-or of an Array (Easy)
- 693. Binary Number with Alternating Bits (Easy)
- 2657. Find the Prefix Common Array of Two Arrays (Medium)
- 231. Power of Two (Easy)
- 342. Power of Four (Easy)
- 191. Number of 1 Bits (Easy)
- 2595. Number of Even and Odd Bits (Easy)
- 338. Counting Bits (Easy)
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¶
# 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¶
"""
- 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].
"""