-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathbase_conversion.py
More file actions
77 lines (62 loc) · 1.76 KB
/
base_conversion.py
File metadata and controls
77 lines (62 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""
Integer Base Conversion
Convert integers between arbitrary bases (2-36). Supports conversion from
integer to string representation in a given base, and vice versa.
Reference: https://en.wikipedia.org/wiki/Positional_notation
Complexity:
Time: O(log_base(num)) for both directions
Space: O(log_base(num))
"""
from __future__ import annotations
import string
def int_to_base(num: int, base: int) -> str:
"""Convert a base-10 integer to a string in the given base.
Args:
num: The integer to convert.
base: The target base (2-36).
Returns:
String representation of num in the given base.
Examples:
>>> int_to_base(5, 2)
'101'
>>> int_to_base(255, 16)
'FF'
>>> int_to_base(0, 2)
'0'
"""
is_negative = False
if num == 0:
return "0"
if num < 0:
is_negative = True
num *= -1
digit = string.digits + string.ascii_uppercase
res = ""
while num > 0:
res += digit[num % base]
num //= base
if is_negative:
return "-" + res[::-1]
return res[::-1]
def base_to_int(str_to_convert: str, base: int) -> int:
"""Convert a string in a given base to a base-10 integer.
Args:
str_to_convert: The string representation of the number.
base: The base of the input string (2-36).
Returns:
The base-10 integer value.
Examples:
>>> base_to_int('101', 2)
5
>>> base_to_int('FF', 16)
255
"""
digit = {}
for ind, char in enumerate(string.digits + string.ascii_uppercase):
digit[char] = ind
multiplier = 1
res = 0
for char in str_to_convert[::-1]:
res += digit[char] * multiplier
multiplier *= base
return res