Python Calculate the Reverse of a Number

Document 对象参考手册Python3 Examples

In this example, we will write a Python function to reverse an integer. For example, input 123, output 321.

Example

def reverse_number(n):
    reversed_num = 0
    while n > 0:
        digit = n % 10
        reversed_num = reversed_num * 10 + digit
        n = n // 10
    return reversed_num

# Test function
number = 12345
print("The reversed number is:", reverse_number(number))

Code explanation:

  1. reverse_numberThe function takes an integernas a parameter.
  2. reversed_numInitialized to 0, used to store the reversed number.
  3. whileThe loop continues whilenis greater than 0.
  4. In each iteration,digitgetnthe last digit of (vian % 10)。
  5. reversed_numupdated toreversed_num * 10 + digit, thus addingdigitto the end ofreversed_num.
  6. nupdated ton // 10, thus removingnthe last digit of .
  7. After the loop ends, returnreversed_num, which is the reversed number.

Output:

反转后的数字是: 54321

Document 对象参考手册Python3 Examples

Other Extensions