Convert an Integer Decimal Number to a Binary Number as str. >>> decimal_to_binary_iterative(0) '0b0' >>> decimal_to_binary_iterative(2) '0b10' >>> decimal_to_binary_iterative(7) '0b111' >>> decimal_to_binary_iterative(35) '0b100011' >>> # negatives work too
(num: int)
| 2 | |
| 3 | |
| 4 | def decimal_to_binary_iterative(num: int) -> str: |
| 5 | """ |
| 6 | Convert an Integer Decimal Number to a Binary Number as str. |
| 7 | >>> decimal_to_binary_iterative(0) |
| 8 | '0b0' |
| 9 | >>> decimal_to_binary_iterative(2) |
| 10 | '0b10' |
| 11 | >>> decimal_to_binary_iterative(7) |
| 12 | '0b111' |
| 13 | >>> decimal_to_binary_iterative(35) |
| 14 | '0b100011' |
| 15 | >>> # negatives work too |
| 16 | >>> decimal_to_binary_iterative(-2) |
| 17 | '-0b10' |
| 18 | >>> # other floats will error |
| 19 | >>> decimal_to_binary_iterative(16.16) # doctest: +ELLIPSIS |
| 20 | Traceback (most recent call last): |
| 21 | ... |
| 22 | TypeError: 'float' object cannot be interpreted as an integer |
| 23 | >>> # strings will error as well |
| 24 | >>> decimal_to_binary_iterative('0xfffff') # doctest: +ELLIPSIS |
| 25 | Traceback (most recent call last): |
| 26 | ... |
| 27 | TypeError: 'str' object cannot be interpreted as an integer |
| 28 | """ |
| 29 | |
| 30 | if isinstance(num, float): |
| 31 | raise TypeError("'float' object cannot be interpreted as an integer") |
| 32 | if isinstance(num, str): |
| 33 | raise TypeError("'str' object cannot be interpreted as an integer") |
| 34 | |
| 35 | if num == 0: |
| 36 | return "0b0" |
| 37 | |
| 38 | negative = False |
| 39 | |
| 40 | if num < 0: |
| 41 | negative = True |
| 42 | num = -num |
| 43 | |
| 44 | binary: list[int] = [] |
| 45 | while num > 0: |
| 46 | binary.insert(0, num % 2) |
| 47 | num >>= 1 |
| 48 | |
| 49 | if negative: |
| 50 | return "-0b" + "".join(str(e) for e in binary) |
| 51 | |
| 52 | return "0b" + "".join(str(e) for e in binary) |
| 53 | |
| 54 | |
| 55 | def decimal_to_binary_recursive_helper(decimal: int) -> str: |