Skip to content

Instantly share code, notes, and snippets.

@alice17
Created December 14, 2022 10:45
Show Gist options
  • Select an option

  • Save alice17/9da88e3bce843880780506af570a4441 to your computer and use it in GitHub Desktop.

Select an option

Save alice17/9da88e3bce843880780506af570a4441 to your computer and use it in GitHub Desktop.
f (int) ->
# hamming weight
# time complexity O(log(n))
def hamming_weight(num: int) -> int:
res = 0
while num > 0:
is_odd = num & 1 # 1 (true) if odd, 0 otherwise
if is_odd:
res += 1
num = num // 2
return res
hamming_weight(7) # 111
def even_parity(num: int) -> bool:
# return true if the number of bits it's even
return not (hamming_weight(num) & 1)
def check_parity(num: int, parity: bool) -> bool:
check = even_parity(num)
return check == parity
# 123 -> 321
# -123 -> -321
def reverse_digits(num: int) -> int:
res = 0
is_neg = num < 0 # false
num = abs(num) # num=12
while num > 0:
res = res * 10 # 0, 20
res += (num % 10) # res=2, 21
num = num // 10 # num=1, 0
if is_neg:
return - res
return res
def check_palindrome(num: int) -> bool:
return num == reverse_digits(num)
# O(log(b)) time
# O(log(b)) space
def speedy_power(a, b):
if b == 1:
return a
else:
c = a * a
answer = speedy_power(c, b // 2)
if b & 1:
return a * answer
else:
return answer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment