Back to questions
Given an integer , return its string representation in base 13.
In case you don’t use base 13 that much (who does, right?), here’s a quick rundown: just like base 10 uses digits from 0 to 9. But also for 10, 11 and 12, we use the letters A, B, and C.
For example:
If you’re not familiar with how base conversion from decimal (base 10) to another base works, here's the process:
Let’s convert 49 to base 13:
Steps:
So, the remainders are . After reversing them, the result is "3A" in base 13.
Here’s the code for the iterative approach where we reverse the result at the end:
In the above code, we are concatenating strings using , and every time we append to a string, Python creates a new string by allocating memory for both the current string and the new character. This operation takes , where is the length of the first string and is the length of the second string.
In the worst case, string concatenation over multiple iterations becomes . This isn’t a big issue for small strings like in this problem, but for longer strings, we can improve the efficiency by using a list and joining it at the end.
Here’s the code using a list for collecting digits, avoiding repeated string concatenations:
This version avoids string concatenation overhead by building the result in a list and reversing it at the end, which operates in time.
The recursive approach follows the same logic as the iterative one but works by breaking the number down step-by-step using recursion. Each recursive call handles a smaller part of the number and builds the result as it "returns" from the recursive calls.
This method handles negative numbers by converting the absolute value to base 13 and then prepending a minus sign.