Problem 504

Abstract / Summary

Given an integer, convert it to its representation in base 7 and return the result as a string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0504.py

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num == 0:
            return "0"

        isNeg = False
        if num < 0:
            isNeg = True
            num = -num

        result = ""
        while num != 0:
            result = result + str(num % 7)
            num //= 7

        result = result[::-1]

        if isNeg:
            return "-" + result
        else:
            return       result
21 lines | 457 bytes | submitted August 13, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 55% (300k+ submissions).

Typical patterns to solve this problem:
  • Math
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method convertToBase7 that transforms a signed 32-bit integer into its base-7 string representation. The algorithm follows a classic divide-and-remainder approach, handling the sign explicitly and treating the value zero as a special case. The implementation builds the digit sequence in reverse order, then flips it to obtain the final result.

Key Steps

Zero-Value Shortcut

if num == 0:
    return "0"

When the input equals zero the method returns the literal string "0" immediately. This avoids entering the conversion loop and guarantees that the output for zero is correctly formatted without a leading sign.

Sign Detection and Normalization

isNeg = False
if num < 0:
    isNeg = True
    num = -num

A Boolean flag records whether the original number was negative. If so, the absolute value is taken so that the subsequent division steps work with a non-negative operand. The flag is later used to prepend a minus sign to the final string.

Digit Extraction Loop

result = ""
while num != 0:
    result = result + str(num % 7)
    num //= 7

Inside the loop the remainder of division by 7 (num % 7) yields the least-significant base-7 digit. The digit is converted to a character and concatenated to the end of result. Because the remainder is produced from the least-significant side, the string grows in reverse order. The integer division num //= 7 discards the processed digit, moving the algorithm toward termination.

Reversal of the Accumulated Digits

result = result[::-1]

After the loop finishes, result holds the digits in reverse (least-significant first). Slicing with a step of -1 produces a new string with the characters in the correct most-significant-first order.

Re-attachment of the Sign

if isNeg:
    return "-" + result
else:
    return       result

If the original number was negative, a leading hyphen is concatenated to the reversed digit string. Otherwise the method returns the digit string unchanged. The extra spaces before result in the else branch are syntactically harmless and do not affect the returned value.

Edge Cases Handled

The routine explicitly covers three important edge conditions:

  • Zero Input - The early return guarantees that the output is exactly "0" rather than an empty string or a sign-prefixed variant.
  • Negative Numbers - By recording the sign before conversion and restoring it afterward, the method correctly produces strings such as "-10" for -7.
  • Large Positive Values - The loop continues until the integer becomes zero, ensuring that any magnitude that fits within the language’s integer type is fully processed, regardless of the number of base-7 digits required.

Performance Optimizations Observed

The algorithm avoids costly front-insertion operations on the result string. Instead of inserting each new digit at the beginning (which would require shifting existing characters), it appends to the end and performs a single reversal at the end. This strategy reduces the amount of data movement during the conversion loop.

The use of integer division (//=) updates the working variable in place, eliminating the need for auxiliary containers or temporary copies of the number. The final slice operation creates a new string only once, after all digits have been collected, which is efficient for typical input sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a box of toys and you want to put them into groups of seven. This code is like a little robot helper that looks at a regular number and changes it into a special code where every group is worth seven.

First, the robot looks to see if the number is zero. If it is, the robot just says zero because that is the easiest answer. If the number is hiding behind a minus sign because it is smaller than zero, the robot remembers that it is a negative number and turns it into a positive number so it is easier to work with.

Now the robot starts making groups. It takes the number and divides it by seven, looking at the leftovers. Those leftovers are like the pieces that do not fit into a group of seven. The robot keeps doing this over and over again, collecting all the leftovers to build a string of digits.

Because the robot finds the end of the number first, it flips the string around so that everything is in the right order. Finally, if the robot remembered that the number was negative at the start, it puts a little minus sign back at the front of the code to finish the job.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 7.00 | σ = 0.83

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Rust Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
everthis JS
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
everthis JavaScript
fartem Ruby
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
ruoru Rust
suxrobGM C#
varunu28 Java
yuanliu666 Kotlin
zfang399 C++
36 links | 23 authors | 11 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

13 solutions   August 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality