Base 7 (LeetCode 504): Solution and Explanation
Given an integer, return its base 7 representation as a string, keeping a leading minus sign for negative numbers.
Intuition
In base 10, n % 10 gives the last digit and n // 10 removes it. Nothing about that is special to 10.
In base 7, n % 7 is the last base 7 digit and n // 7 shifts the number right by one base 7 place. Repeating this peels off every digit.
The digits come out from least significant to most significant, so they have to be reversed before returning.
Two inputs fall outside the loop: 0, which would produce an empty string, and negative numbers, which are easiest to convert by their absolute value and then prefix with a minus sign.
Approach: Repeated division by 7
- If
numis 0, return "0". - Let
n = abs(num)and start an empty list of digits. - While
n > 0, appendn % 7and setn //= 7. - If
numwas negative, append a minus sign. - Return the list reversed and joined.
Step-by-step example
num = 100
- n = 100. 100 = 7 * 14 + 2, so the last digit is 2 and n becomes 14.
- 14 = 7 * 2 + 0, so the next digit is 0 and n becomes 2.
- 2 = 7 * 0 + 2, so the next digit is 2 and n becomes 0. The loop stops.
- The digits came out as 2, 0, 2. Reversed they read "202". Check: 2 * 49 + 0 * 7 + 2 = 100.
Code: Python, Java, C++
1class Solution:
2 def convertToBase7(self, num: int) -> str:
3 if num == 0:
4 return "0"
5 n = abs(num)
6 digits = []
7 while n > 0:
8 digits.append(str(n % 7))
9 n //= 7
10 if num < 0:
11 digits.append("-")
12 return "".join(reversed(digits))1class Solution {
2 public String convertToBase7(int num) {
3 if (num == 0) {
4 return "0";
5 }
6 int n = Math.abs(num);
7 StringBuilder sb = new StringBuilder();
8 while (n > 0) {
9 sb.append(n % 7);
10 n /= 7;
11 }
12 if (num < 0) {
13 sb.append('-');
14 }
15 return sb.reverse().toString();
16 }
17}1class Solution {
2public:
3 string convertToBase7(int num) {
4 if (num == 0) {
5 return "0";
6 }
7 int n = abs(num);
8 string s;
9 while (n > 0) {
10 s += char('0' + n % 7);
11 n /= 7;
12 }
13 if (num < 0) {
14 s += '-';
15 }
16 reverse(s.begin(), s.end());
17 return s;
18 }
19};Time and space complexity
O(log n)
Each iteration divides n by 7, so there are about log base 7 of |num| iterations, at most 9 for the given range.
O(log n)
The output string has one character per base 7 digit, plus a possible sign.
Other approaches
Recursion (time O(log n), space O(log n))
Convert num // 7 recursively and append num % 7. The recursion naturally emits the most significant digit first, so no reversal is needed.
Built-in conversion (time O(log n), space O(log n))
Java has Integer.toString(num, 7) and JavaScript has num.toString(7). They give the same answer but skip the point of the exercise.
Common mistakes
- Returning an empty string for 0 because the loop never runs.
- Using % on a negative number. In Python, -7 % 7 is 0 but -8 % 7 is 6, and in Java or C++ the remainder is negative. Convert the absolute value instead.
- Forgetting to reverse the digits, which gives the answer backwards.
- Putting the minus sign at the end when the digits are not reversed afterwards.
Frequently asked questions
Why does n % 7 give the last base 7 digit?
Any number in base 7 is d_k * 7^k + ... + d_1 * 7 + d_0. Every term except d_0 is a multiple of 7, so the remainder after dividing by 7 is d_0.
How many digits can the answer have?
|num| is at most 10^7, and 7^9 is about 40 million, so the answer has at most 9 digits plus a sign.
Does this work for other bases?
Yes. Replace 7 with any base b from 2 to 10. For bases above 10 you also need letters for digits 10 and up.