2019-07-05 08:36:48 +00:00
|
|
|
"""Convert a Decimal Number to an Octal Number."""
|
|
|
|
|
|
|
|
import math
|
|
|
|
|
|
|
|
# Modified from:
|
|
|
|
# https://github.com/TheAlgorithms/Javascript/blob/master/Conversions/DecimalToOctal.js
|
|
|
|
|
|
|
|
|
2019-12-08 22:27:42 +00:00
|
|
|
def decimal_to_octal(num: int) -> str:
|
|
|
|
"""Convert a Decimal Number to an Octal Number.
|
2020-05-22 06:10:11 +00:00
|
|
|
|
2020-06-16 08:09:19 +00:00
|
|
|
>>> all(decimal_to_octal(i) == oct(i) for i
|
|
|
|
... in (0, 2, 8, 64, 65, 216, 255, 256, 512))
|
2019-12-08 22:27:42 +00:00
|
|
|
True
|
|
|
|
"""
|
2019-07-05 08:36:48 +00:00
|
|
|
octal = 0
|
|
|
|
counter = 0
|
|
|
|
while num > 0:
|
|
|
|
remainder = num % 8
|
|
|
|
octal = octal + (remainder * math.pow(10, counter))
|
|
|
|
counter += 1
|
|
|
|
num = math.floor(num / 8) # basically /= 8 without remainder if any
|
|
|
|
# This formatting removes trailing '.0' from `octal`.
|
2019-12-08 22:27:42 +00:00
|
|
|
return f"0o{int(octal)}"
|
2019-07-05 08:36:48 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2020-01-18 12:24:33 +00:00
|
|
|
"""Print octal equivalents of decimal numbers."""
|
2019-07-05 08:36:48 +00:00
|
|
|
print("\n2 in octal is:")
|
|
|
|
print(decimal_to_octal(2)) # = 2
|
|
|
|
print("\n8 in octal is:")
|
|
|
|
print(decimal_to_octal(8)) # = 10
|
|
|
|
print("\n65 in octal is:")
|
|
|
|
print(decimal_to_octal(65)) # = 101
|
|
|
|
print("\n216 in octal is:")
|
|
|
|
print(decimal_to_octal(216)) # = 330
|
|
|
|
print("\n512 in octal is:")
|
|
|
|
print(decimal_to_octal(512)) # = 1000
|
|
|
|
print("\n")
|
|
|
|
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2019-07-05 08:36:48 +00:00
|
|
|
main()
|