play with bits

This commit is contained in:
bt3gl 2023-07-29 20:18:30 -07:00 committed by GitHub
parent c77eb0dd00
commit 4b22537ee7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,16 @@
def convert_to_any_base(base: int, num: int) -> str:
if num == 0:
return "0"
n = abs(num)
result = ""
while n:
result += str(n % base)
n //= base
if num < 0:
result += '-'
return result[::-1]

View File

@ -0,0 +1,18 @@
def convert_to_hex(num: int) -> str:
hex_chars = "0123456789abcdef"
size = 32
base = 16
if num == 0:
return "0"
if num < 1:
num += 2**size
result = ""
while num:
result += hex_chars[num % base]
num //= base
return result[::-1]

View File

@ -0,0 +1,12 @@
def count_ones(n: int) -> int:
counter = 0
while n:
if n & 1:
counter += 1
n >>= 1
return counter

View File

@ -0,0 +1,10 @@
def reverse_bits(n: int) -> int:
result, base = 0, 31
while n:
result += (n & 1) << base
n >>= 1
base -= 1
return result

View File

@ -0,0 +1,17 @@
def get_sum(self, a: int, b: int) -> int:
if a == -b:
return 0
if abs(a) > abs(b):
a, b = b, a
if a < 0:
return - get_sum(-a, -b)
while b:
c = a & b
a, b = a ^ b, c << 1
return a