Base 7 (LeetCode 504): Solution and Explanation

Easy
Math
String

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

  1. If num is 0, return "0".
  2. Let n = abs(num) and start an empty list of digits.
  3. While n > 0, append n % 7 and set n //= 7.
  4. If num was negative, append a minus sign.
  5. Return the list reversed and joined.

Step-by-step example

num = 100
  1. n = 100. 100 = 7 * 14 + 2, so the last digit is 2 and n becomes 14.
  2. 14 = 7 * 2 + 0, so the next digit is 0 and n becomes 2.
  3. 2 = 7 * 0 + 2, so the next digit is 2 and n becomes 0. The loop stops.
  4. 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))
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.