Given an integer num, write it in base 7 and return the result as a string.
Base 7 uses only the digits 0 to 6, and each place is worth 7 times the place to its right. A negative number keeps its minus sign in front.
Example 1
Input: num = 250 Output: "505" Why: 5·49 + 0·7 + 5·1 = 250
2 more examples and the constraints
Example 2
Input: num = -15 Output: "-21" Why: 15 = 2·7 + 1, and the sign stays in front
Example 3
Input: num = 0 Output: "0" Why: zero is a single 0 digit in any base
Constraints
- -10,000,000 ≤ num ≤ 10,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Place values from the topO(log n)
- Repeated divisionO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for num = 10,000,000 | Verdict |
|---|---|---|---|
| Place values from the top | O(log n) | Fine; climbs up, then down | |
| Repeated division | O(log n) | Best; one pass |
n = |num|. Both are tiny: 10,000,000 has only 9 base-7 digits.
Edge cases to test
- Zero. num = 0 must give "0", not an empty string.
- Negative numbers. -15 gives "-21": convert 15 and put the sign in front.
- Exact powers of 7. 49 gives "100"; the zero digits in the middle and end must appear.
- Single digits. Anything from -6 to 6 is its own digit, such as "6" or "-4".
- Largest input. 10,000,000 gives "150666343", nine digits.
Common mistakes
- Forgetting the 0 case, so the loop never runs and the answer is an empty string.
- Taking
%of a negative number, which gives negative or wrapped digits depending on the language. - Joining the digits in the order they were found, which writes the number backwards.
How to talk through it
- 1Clarify. Can num be negative or zero? Is the answer a string with a leading minus sign?
- 2Recall the method. n % 7 is the last digit and n // 7 drops it, just like base 10.
- 3Handle the sign. Convert the absolute value and add the sign at the end.
- 4Code it. One loop collecting remainders, then reverse and join.
- 5Test out loud. Try 0, 49 and a negative number before you finish.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?