Python easy understand solution


  • 14

    Recursion will simplify the function.

    def convertTo7(self, num):
        if num < 0: return '-' + self.convertTo7(-num)
        if num < 7: return str(num)
        return self.convertTo7(num // 7) + str(num % 7)
    
    

    General iteration methode:

    def convertTo7(self, num):
        if num == 0: return '0'
        n, res = abs(num), ''
        while n:
          res = str(n % 7) + res
          n //= 7
        return res if num > 0 else '-' + res

  • 0
    R

    You can use divmod(num, 7) in the method instead of using \\ and %

            res = divmod(num,7)
            return self.convertToBase7(res[0]) + str(res[1])
    

  • 2

    @revanth6 Does that have any advantage? I only see disadvantages.


  • 0
    R

    Javascript version:

    var convertToBase7 = function(num) {
        if( num < 0) {
            return '-' + convertToBase7(-num);
        }
        if(num < 7) return num + ""
        return convertToBase7((num / 7)>>0) + "" + (num % 7)
    };
    

    Golang version:

    import "strconv"
    
    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)
    }
    

  • 0
    L

    @StefanPochmann advantage: num, res = divmod(num, 7), disadvantage: res = divmod(num,7)


  • 0

    @lanjiann But what's the advantage?


  • 0
    T

    @lee215 said in Python easy understand solution:

    return res if num >= 0 else '-' + res

    num won't ever be equal to 0 at that point, you only need > in the comparison


  • 0

    @tanoabeleyra I agree.


  • -3
    P

    I wrote a relatively straightforward Python snippet - but it is returning some weird values - when I run the code here. Basically I see return values prepended with zeroes
    "0.20.02" instead of "202".

    It works perfectly fine on my local python instance. Any ideas what I am missing here?
    """
    arr = ""
    radix = 7
    if num < radix:
    arr += str(num)
    while num >= radix:
    arr += str(num%radix)
    num = math.floor(num/radix)
    if num < radix:
    arr += str(num)
    return arr[::-1]
    """


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.