Of course. Here is a solution to convert an integer to its binary string representation without using built-in functions like bin() or format().
Approach
The standard algorithm for converting a decimal integer to binary is based on repeated division by 2.
- Repeated Division: Continuously divide the number by 2 and keep track of the remainder. The remainder will always be either 0 or 1.
- Collect Remainders: These remainders, when read in reverse order of their calculation, form the binary representation of the number.
- Termination: The process stops when the number becomes 0.
Example: Convert 13 to Binary
13 / 2 = 6, Remainder = 1
6 / 2 = 3, Remainder = 0
3 / 2 = 1, Remainder = 1
1 / 2 = 0, Remainder = 1
Reading the remainders from bottom to top gives us 1101, which is the binary representation of 13.
Implementation
We can implement this by building a string. To avoid having to reverse the string at the end, we can prepend each new remainder to the front of our result string. We also need to handle edge cases like the number 0 and negative numbers.
def integer_to_binary(n: int) -> str:
"""
Converts an integer to its binary representation as a string.
This implementation does not use any built-in conversion functions like bin().
Args:
n (int): The integer to convert.
Returns:
str: The binary string representation of the integer.
"""
# Edge case: if the input is 0, its binary is "0"
if n == 0:
return "0"
# Handle negative numbers by converting the absolute value
# and prepending a minus sign.
is_negative = n < 0
if is_negative:
n = -n
binary_string = ""
while n > 0:
# Get the remainder of the division by 2 (0 or 1)
remainder = n % 2
# Prepend the remainder to the front of the string
binary_string = str(remainder) + binary_string
# Update the number using integer division
n = n // 2
if is_negative:
return "-" + binary_string
else:
return binary_string
# --- Example Usage ---
if __name__ == "__main__":
print(f"13 in binary is: {integer_to_binary(13)}") # Expected: 1101
print(f"42 in binary is: {integer_to_binary(42)}") # Expected: 101010
print(f"0 in binary is: {integer_to_binary(0)}") # Expected: 0
print(f"1 in binary is: {integer_to_binary(1)}") # Expected: 1
print(f"-13 in binary is: {integer_to_binary(-13)}") # Expected: -1101
print(f"-42 in binary is: {integer_to_binary(-42)}") # Expected: -101010
Explanation
- Handle Zero: The code first checks for the special case
n == 0 and returns "0" immediately, as the main loop would not execute for an input of 0.
- Handle Negatives: It checks if the number is negative. If so, it sets a flag
is_negative to True and proceeds with the absolute value of n. This separates the sign from the conversion logic.
- Main Loop (
while n > 0):
remainder = n % 2: The modulo operator (%) gives us the remainder of n divided by 2. This is the next binary digit.
binary_string = str(remainder) + binary_string: The remainder (0 or 1) is converted to a string and added to the beginning of our result string. This builds the binary string in the correct order without needing a final reversal step.
n = n // 2: We perform integer division (//) to get the next number to work with.
- Return Value: After the loop finishes, if the original number was negative (checked via the
is_negative flag), a "-" is prepended to the final binary string before returning. Otherwise, the string is returned as is.