简体   繁体   English

Python:如何使用递归反转整数

[英]Python: How to reverse integers using recursion

I am given a problem where I have to reverse given digits using recursion only, but the problem is when I try to print out the integer reversed, for example if the integer was 1234, it would print the reversed numbers partially once at a time, eg: 21, 321, 4321. How can I fix this so that it can print 4321 in one go?我遇到了一个问题,我必须仅使用递归来反转给定的数字,但问题是当我尝试打印出 integer 反转时,例如,如果 integer 是 1234,它会一次打印部分反转的数字,例如:21、321、4321。我该如何解决这个问题,以便它可以在一个 go 中打印 4321?

def reverse_digits(n):
    if n < 10:
        return n
    else:
        reverse = str(n % 10) + str(reverse_digits(n // 10))
        print(reverse)
        return reverse

Just don't have the function print anything at all, only returns the value, and you can print it when you call it:只是根本没有 function 打印任何东西,只返回值,调用时可以打印:

def reverse_digits(n):
    if n < 10:
        return n
    else:
        reverse = str(n % 10) + str(reverse_digits(n // 10))
        return reverse

print(reverse_digits(1234))

Output: Output:

4321

If you still want the function to print, you can print each digit separately in the same line (using end='' in the print function):如果您仍然希望 function 打印,您可以在同一行中单独打印每个数字(在打印函数中使用end='' ):

def reverse_digits(n):
    if n < 10:
        print(n)  #  print the very last digit and add a newline
        return n
    else:
        print(n % 10, end='')  #  print the last digit so far and stay on the same line
        reverse = str(n % 10) + str(reverse_digits(n // 10))
        return reverse

reverse_digits(1234)

Output: Output:

4321

Remove the print from within the function:从 function 中删除打印:

def reverse_digits(n):
    if n < 10:
        return n
    else:
        reverse = str(n % 10) + str(reverse_digits(n // 10))
        return reverse
print(reverse_digits(1234))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM