We repeatedly divide the number by 2 and build the binary string from the remainders using recursion.
- Base case: If
n == 0, return "0". Ifn == 1, return "1". - Recursive step: Return
decimal_to_binary(n // 2)+str(n % 2).
- Time Complexity: O(log N).
- Space Complexity: O(log N) (recursion stack).
def decimal_to_binary(n):
if n == 0:
return "0"
if n == 1:
return "1"
return decimal_to_binary(n // 2) + str(n % 2)