Python Compute the Reverse of a Number
In this example we will write a Python function that reverses an integer. For example, given the input 123 it outputs 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 the function
number
=
12345
(
"The reversed number is:"
,
reverse_number
(
number
)
)
Code analysis:
reverse_numberThe function takes an integernas its argument.reversed_numInitialize to 0 to store the reversed number.whileThe loop continues whilenContinue while it is greater than 0.- In each iteration,
digitObtain thenthe last digit of (obtained withn % 10)。 reversed_numis updated toreversed_num * 10 + digit, so that thedigitis added toreversed_numend of thenis updated ton // 10, which removes thenlast digit of .- After the loop ends, return
reversed_num, that is, the reversed number.
Output result:
反转后的数字是: 54321
Python3 Examples