Skip to content
← All posts

Base 7: Number Base Conversion

5 min read
leetcodeproblemeasymath

LeetCode Base 7 (Problem 504) asks you to convert an integer into its base 7 string representation. This is a classic number base conversion problem that teaches you the repeated division algorithm, one of the most fundamental patterns in computer science and math.

The problem

Given an integer num, return a string of its base 7 representation.

  • Input: num = 100

  • Output: "202"

  • Explanation: 2 * 49 + 0 * 7 + 2 * 1 = 100

  • Input: num = -7

  • Output: "-10"

  • Explanation: The negative sign is preserved. 1 * 7 + 0 * 1 = 7, so -7 in base 7 is "-10".

Converting 100 to base 7 via repeated division100dividend÷7divisor=14quotientR2remainder14dividend÷7divisor=2quotientR0remainder2dividend÷7divisor=0quotientR2remainderRead remainders bottom-up:"202"
Divide 100 by 7 repeatedly. Collect remainders (2, 0, 2) and read them in reverse to get "202".

The approach

The algorithm for converting a number to any base follows a simple recipe: repeatedly divide by the base and collect the remainders. Each remainder becomes one digit in the result, starting from the least significant (rightmost) digit.

For base 7 specifically:

  1. Handle the special case where num is 0 (return "0")
  2. If the number is negative, note the sign and work with the absolute value
  3. While the number is greater than 0, divide by 7 and save the remainder
  4. Reverse the collected remainders to form the final string
  5. Prepend a minus sign if the original number was negative

This is the same algorithm you would use to convert to binary (divide by 2), octal (divide by 8), or hexadecimal (divide by 16). The only difference is the divisor.

The remainders come out in reverse order. The first remainder you compute is the ones digit (rightmost), and the last remainder is the most significant digit (leftmost). You need to reverse them or build the string from right to left.

Step-by-step walkthrough

Let's trace through the conversion of num = 100 to base 7, showing each division step and the growing list of collected digits.

Step 1: 100 / 7 = 14 remainder 2

100÷ 7 =14remainder2digits = [2]

The first remainder (2) becomes the rightmost digit. The quotient (14) carries forward to the next division.

Step 2: 14 / 7 = 2 remainder 0

14÷ 7 =2remainder0digits = [2, 0]

The second remainder (0) becomes the middle digit. The quotient (2) is still not zero, so we continue.

Step 3: 2 / 7 = 0 remainder 2

2÷ 7 =0remainder2digits = [2, 0, 2]

The quotient is now 0, so this is the last division. The remainder (2) becomes the leftmost digit.

Step 4: Reverse the collected remainders

collected:202"202"

Reading [2, 0, 2] in reverse gives '202'. That is 100 expressed in base 7.

Observations:

  • Each division extracts one digit of the base-7 representation
  • The quotient becomes the input for the next iteration
  • When the quotient reaches 0, you have extracted all digits
  • The remainders are always in the range [0, 6] for base 7

The code

def convert_to_base7(num):
    if num == 0:
        return "0"

    negative = num < 0
    num = abs(num)
    digits = []

    while num > 0:
        digits.append(str(num % 7))
        num //= 7

    if negative:
        digits.append("-")

    return "".join(reversed(digits))

Here is what each part does:

  • Line 2-3: If the input is 0, return "0" immediately. Zero is the same in every base.
  • Line 5-6: Record whether the number is negative, then work with its absolute value so the mod/div logic stays clean.
  • Line 7: Initialize an empty list to collect digit characters.
  • Line 9-11: The core loop. num % 7 gives the current least-significant digit, and num //= 7 removes it by integer division. Repeat until nothing remains.
  • Line 13-14: If the original number was negative, append the minus sign (it will end up at the front after reversal).
  • Line 16: Reverse the collected digits and join them into a string.

Complexity analysis

MetricValue
TimeO(log_7 n)
SpaceO(log_7 n)

The number of digits in base 7 is proportional to log base 7 of n. Each iteration of the loop produces one digit, so the loop runs O(log_7 n) times. The space comes from storing those digits in a list before joining them into a string.

For the constraint range of this problem (integers up to about 10^7), the loop runs at most 9 or 10 times, so performance is never a concern.

Building blocks

The repeated division pattern is the single building block here, and it appears in many related problems.

Repeated division for base conversion

Any time you need to express a number in a different base, you use the same algorithm: divide by the target base, collect the remainder, repeat with the quotient. You have seen variations of this in:

The mod operation extracts the current digit, and integer division shifts the number one position to the right in the target base. Once you internalize this pattern, every base conversion problem becomes the same loop with a different divisor.

Edge cases

  • num = 0: Must return "0", not an empty string. The loop body never executes when num is 0, so you need the explicit check at the start.
  • Negative numbers (e.g., num = -7): Strip the sign, convert the absolute value, then prepend "-" to the result. The answer for -7 is "-10".
  • num = -7 specifically: 7 % 7 = 0 and 7 // 7 = 1, then 1 % 7 = 1 and 1 // 7 = 0. Digits collected are [0, 1], reversed to "10", with sign prepended: "-10".
  • num = 1: 1 % 7 = 1, 1 // 7 = 0. Result is "1".
  • num = 6: The largest single base-7 digit. 6 % 7 = 6, 6 // 7 = 0. Result is "6".
  • num = 7: The first two-digit base-7 number. 7 % 7 = 0, 7 // 7 = 1, 1 % 7 = 1, 1 // 7 = 0. Result is "10".

Two common mistakes: forgetting to handle num = 0 (which would return an empty string) and applying the modulo operation to negative numbers directly (which behaves differently across languages). Always convert to positive first, then handle the sign separately.

From understanding to recall

Base conversion by repeated division is one of those patterns that feels obvious when you read it but can trip you up under time pressure if you have not practiced it recently. Which digit goes where? Do you reverse at the end or build from the front? How do you handle negatives and zero?

Spaced repetition solves this. CodeBricks drills the repeated division pattern at increasing intervals so that the next time you see a base conversion problem, you reach for the right loop structure without hesitation. You type the solution from scratch each time, building muscle memory for the mod-and-divide rhythm.

Related posts

  • Reverse Integer - Uses the same mod/div pattern to peel digits off from right to left
  • Palindrome Number - Digit extraction without string conversion, same underlying mod arithmetic
  • Excel Sheet Column Title - Base conversion with a twist (1-indexed base 26), same repeated division loop

Base conversion is one of the foundational math patterns that shows up across many problems. Once you have drilled it enough to write it from memory, you will recognize it instantly in disguised forms like column titles, number-to-string conversions, and encoding schemes.