To solve this problem, we need to convert an integer into its binary string representation without using any standard library functions. The solution should handle both positive and negative integers, as well as zero.
Approach
- Handle Zero Case: If the input integer is zero, directly return "0".
- Check for Negative Numbers: If the number is negative, note the sign and work with its absolute value for the conversion process.
- Conversion Process:
- Use repeated division by 2 to collect remainders, which represent the binary digits in reverse order.
- Reverse the collected remainders to get the correct binary representation.
- Construct Result: Combine the binary digits into a string and prepend a minus sign if the original number was negative.
Solution Code
def int_to_binary(n: int) -> str:
"""
Converts an integer to its binary string representation without using standard library functions.
Args:
n (int): The integer to convert.
Returns:
str: The binary string representation of the integer.
"""
if n == 0:
return "0"
is_negative = False
if n < 0:
is_negative = True
n = -n
binary_digits = []
while n > 0:
remainder = n % 2
binary_digits.append(str(remainder))
n = n // 2
# Reverse to get the correct order
binary_digits.reverse()
binary_str = ''.join(binary_digits)
if is_negative:
binary_str = '-' + binary_str
return binary_str
# Example usage
print(int_to_binary(5)) # Output: "101"
print(int_to_binary(-5)) # Output: "-101"
print(int_to_binary(0)) # Output: "0"
print(int_to_binary(6)) # Output: "110"
Explanation
- Zero Handling: The function immediately returns "0" if the input is zero.
- Negative Check: If the input is negative, the function flags it and works with the absolute value to avoid complications with negative modulo operations.
- Binary Digit Collection: By repeatedly dividing the number by 2 and collecting remainders, we gather the binary digits from least significant to most significant. Reversing this list gives the correct order.
- Result Construction: The collected digits are joined into a string, and a minus sign is added if the original number was negative.
This approach efficiently converts the integer to binary using basic arithmetic operations, ensuring no standard library functions are used. The time complexity is O(log n) due to the repeated division, and the space complexity is O(log n) for storing the binary digits.