504 Base 7

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def convertToBase7(self, num: int) -> str:
        sign = '-' if num < 0 else ''
        num = abs(num)
        res = ''
        while num:
            res = str(num % 7) + res
            num //= 7
        return sign + res or '0'

'''
Recursion
'''
class Solution:
    def convertToBase7(self, num: int) -> str:
        if n < 0:
            return '-' + self.convertToBase7(-n)
        if n < 7:
            return str(n)
        return self.convertToBase7(n // 7) + str(n % 7)
1
2
3
4
5
6
7
8
9
func convertToBase7(num int) string {
    if num < 0 {
        return "-" + convertToBase7(-num)
    }
    if num < 7 {
        return strconv.Itoa(num)
    }
    return convertToBase7(num/7) + strconv.Itoa(num%7)
}