代码之家  ›  专栏  ›  技术社区  ›  DCR

使用递归将int转换为字符串

  •  1
  • DCR  · 技术社区  · 10 月前

    我知道在python中,我们可以使用str()轻松地将int转换为字符串。我想使用递归而不是使用str()将int转换为字符串。我想出了以下方法,看起来很有效,但看起来过于复杂。有没有更干净、更优雅、更高效的算法?

    def intTOstring(n,text=""):
        if n == 0:
            return text
        elif n < 10 and n > 0:
            return text + chr(n+48)
        else:
            x = n
            i = 0
            while(x >= 10):
                x = x // 10
                i += 1            
            n = n - x*10**i        
            text = text + chr(x+48)
            if n < 10**(i-1):
                text = text + chr(48)
            return intTOstring(n,text)
        
    print(intTOstring(125))
    
    2 回复  |  直到 10 月前
        1
  •  2
  •   Andrej Kesely    10 月前

    我会这样做:

    def int_to_string(n):
        i, j = n // 10, n % 10
        return (int_to_string(i) if i > 0 else "") + chr(j + 48)
    
    
    s = int_to_string(125)
    print(s, type(s))
    

    打印:

    125 <class 'str'>
    
        2
  •  1
  •   Hoxha Alban    10 月前

    是的,你可以使用模数来简化你的函数

    def intToString(n):
        if not n:
            return ""
        return intToString(n // 10) + chr(48 + n % 10)