FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithms-python/algorithms/maths/base_conversion.py at master · Mu-L/algorithms-python · GitHub
Mu-L
/
algorithms-python
Public
forked from
keon/algorithms
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithms-python
/
algorithms
/
maths
/
base_conversion.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
49 lines (42 loc) · 1.01 KB
Breadcrumbs
algorithms-python
/
algorithms
/
maths
/
base_conversion.py
Copy path
File metadata and controls
49 lines (42 loc) · 1.01 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
Integer base conversion algorithm
int_to_base(5, 2) return '101'.
base_to_int('F', 16) return 15.
"""
import
string
def
int_to_base
(
num
,
base
):
"""
:type num: int
:type base: int
:rtype: str
"""
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
,
base
):
"""
Note : You can use int() built-in function instead of this.
:type str_to_convert: str
:type base: int
:rtype: int
"""
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
Back
|
FazBrowse Home
|
New Git URL