Skip to content

Commit 696cd47

Browse files
octal_to_decimal converter (TheAlgorithms#2399)
* Create octal_to_decimal octal to decimal converter * Update octal_to_decimal * Update conversions/octal_to_decimal Co-authored-by: Christian Clauss <cclauss@me.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 4d0a8f2 commit 696cd47

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

conversions/octal_to_decimal

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
def oct_to_decimal(oct_string: str) -> int:
2+
"""
3+
Convert a octal value to its decimal equivalent
4+
5+
>>> oct_to_decimal("12")
6+
10
7+
>>> oct_to_decimal(" 12 ")
8+
10
9+
>>> oct_to_decimal("-45")
10+
-37
11+
>>> oct_to_decimal("2-0Fm")
12+
ValueError: Non-octal value was passed to the function
13+
>>> oct_to_decimal("")
14+
ValueError: Empty string value was passed to the function
15+
>>> oct_to_decimal("19")
16+
ValueError: Non-octal value was passed to the function
17+
"""
18+
oct_string = str(oct_string).strip()
19+
if not oct_string:
20+
raise ValueError("Empty string was passed to the function")
21+
is_negative = oct_string[0] == "-"
22+
if is_negative:
23+
oct_string = oct_string[1:]
24+
if not all(0 <= int(char) <= 7 for char in oct_string):
25+
raise ValueError("Non-octal value was passed to the function")
26+
decimal_number = 0
27+
for char in oct_string:
28+
decimal_number = 8 * decimal_number + int(char)
29+
if is_negative:
30+
decimal_number = -decimal_number
31+
return decimal_number
32+
33+
34+
if __name__ == "__main__":
35+
from doctest import testmod
36+
37+
testmod()

0 commit comments

Comments
 (0)