mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-30 12:46:11 -04:00
play with bits
This commit is contained in:
parent
c77eb0dd00
commit
4b22537ee7
16
bit_manipulation/convert_any_base.py
Normal file
16
bit_manipulation/convert_any_base.py
Normal 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]
|
18
bit_manipulation/convert_to_hex.py
Normal file
18
bit_manipulation/convert_to_hex.py
Normal 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]
|
12
bit_manipulation/count_1s.py
Normal file
12
bit_manipulation/count_1s.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
def count_ones(n: int) -> int:
|
||||||
|
|
||||||
|
counter = 0
|
||||||
|
|
||||||
|
while n:
|
||||||
|
|
||||||
|
if n & 1:
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
n >>= 1
|
||||||
|
|
||||||
|
return counter
|
10
bit_manipulation/reverse_bits.py
Normal file
10
bit_manipulation/reverse_bits.py
Normal 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
|
17
bit_manipulation/sum_with_bitwise.py
Normal file
17
bit_manipulation/sum_with_bitwise.py
Normal 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
|
Loading…
x
Reference in New Issue
Block a user