↓Skip to main content
  1. LeetCode/

LeetCode 504: Base 7

·1 min· ·
LeetCode Easy Math String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-25

  • Submissions: Runtime Error → Accepted

Approach
#

Base conversion (Math Template 7): repeatedly take % 7 of abs(num) for the lowest digit and // 7 to move on, reverse, and prepend - for negatives. With num = 0 the loop never runs, so return "0" directly.

My Attempts
#

The first submission pasted the wrong problem’s code, a BST-mode solution (AttributeError). Seconds later the right code passed.

Solution
#

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num == 0:
            return "0"
        n, digits = abs(num), []
        while n:
            digits.append(str(n % 7))
            n //= 7
        return ("-" if num < 0 else "") + "".join(reversed(digits))

Complexity
#

Time O(log n), space O(log n).

Mistakes to Avoid
#

  • Handle 0 separately.
  • Work on the absolute value; Python’s % gives a non-negative remainder for negatives.

Interview Explanation
#

I take remainders mod 7 of the absolute value for each digit, divide, reverse at the end, and add the sign; 0 returns directly. Time O(log n).

Related

LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 405: Convert a Number to Hexadecimal
·2 mins
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 note: add 2^32 to a negative number to get its two’s complement, then take 4 bits at a time (% 16); handle 0 separately
LeetCode 412: Fizz Buzz
·1 min
LeetCode Easy Math String Simulation
LeetCode 412 note: check multiples of 15 first, then 5 and 3; multiples need %, not //
LeetCode 171: Excel Sheet Column Number
·1 min
LeetCode Easy Math String
LeetCode 171 note: scan left to right with res = res × 26 + letter value (A = 1)
LeetCode 168: Excel Sheet Column Title
·2 mins
LeetCode Easy Math String
LeetCode 168 note: Excel columns are base 26 without a zero digit; take (n - 1) % 26 as the letter, then n = (n - 1) // 26
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2