
python
class Solution:
def smallestNumber(self, n: int) -> int:
return (1 << n.bit_length()) - 1

python
class Solution:
def minChanges(self, n: int, k: int) -> int:
return -1 if n & k != k else (n ^ k).bit_count()

python
class Solution:
def sortByBits(self, arr: List[int]) -> List[int]:
return sorted(arr, key=lambda x: (x.bit_count(), x))

python
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count('1')

python
class Solution:
def minBitFlips(self, start: int, goal: int) -> int:
# return bin(start ^ goal) .count('1')
return (start ^ goal).bit_count()

python
class Solution:
def numberOfSteps(self, num: int) -> int:
return num.bit_length() + num.bit_count() - 1 if num else 0

python
class Solution:
def findComplement(self, num: int) -> int:
return num ^ ((1 << num.bit_length()) - 1)

python
class Solution:
def bitwiseComplement(self, n: int) -> int:
Nbit = bin(n)
return 2**len(Nbit[2:]) - 1 - n

python
idx_map = {1<<i:i for i in range(30)}
class Solution:
def binaryGap(self, n: int) -> int:
def lowbit(x):
return x & (-x)
last, ans = inf, 0
while n:
n -= (cur := lowbit(n))
ans, last = max(ans, idx_map[cur] - last), idx_map[cur]
return ans

python
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
return not (a := n ^ (n >> 1)) & (a + 1)

python
class Solution:
def xorOperation(self, n: int, start: int) -> int:
xor_n = lambda n: (n, 1, n + 1, 0)[n % 4]
a = start // 2
b = n & start & 1
return (xor_n(a + n - 1) ^ xor_n(a - 1)) * 2 + b