Given an integer num, return a string of its base 7 representation.
Example 1:
Input: num = 100 Output: "202"
Example 2:
Input: num = -7 Output: "-10"
Constraints:
-107 <= num <= 107In #504 Base 7, the goal is to convert a given integer into its representation in base-7. This is a classic number base conversion problem that relies on repeated division and remainder extraction.
The key idea is to repeatedly divide the number by 7 and record the remainder at each step. Each remainder represents a digit in the base-7 representation. These digits are produced from least significant to most significant, so they must be collected and then reversed to form the final result. Special handling is required when the number is 0, since its base-7 representation is simply "0".
Another important detail is dealing with negative numbers. A common approach is to store the sign, convert the absolute value using the same division logic, and then prepend the negative sign to the final string.
This mathematical approach is efficient because the number shrinks by a factor of 7 each step, leading to logarithmic time complexity. The space used mainly comes from storing the resulting digits.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Repeated Division (Base Conversion) | O(log₇ n) | O(log₇ n) |
CodeHelp - by Babbar
Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Problems like Base 7 are common in coding interviews because they test understanding of number systems and basic mathematical manipulation. While the exact question may vary, base conversion logic frequently appears in technical interviews.
The optimal approach is repeated division by 7. At each step, you take the remainder as the next base-7 digit and divide the number by 7 until it becomes zero. The digits are collected in reverse order and then reversed to form the final representation.
A simple string builder or list is sufficient to collect the digits produced by each remainder operation. Since digits are generated in reverse order, you either reverse the result at the end or build the string from the front.
You can first record whether the input number is negative, then convert its absolute value to base 7. After generating the base-7 digits, simply prepend a minus sign to the result if the original number was negative.