Skip to content

504. Base 7

Math String

Problem - Base 7

Easy

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

 

Example 1:

Input: num = 100
Output: "202"

Example 2:

Input: num = -7
Output: "-10"

 

Constraints:

  • -107 <= num <= 107

Solutions

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def convertToBase7(self, num: int) -> str:
        if num == 0:
            return "0"

        if num < 0:
            return "-" + self.convertToBase7(-num)

        result = []
        while num:
            result.append(str(num % 7))
            num //= 7

        return "".join(result[::-1])

Submission Stats:

  • Runtime: 0 ms (100.00%)
  • Memory: 17.8 MB (40.69%)