def reverse_number(n): reversed_number = 0 while n > 0: remainder = n % 10 reversed_number = (reversed_number * 10) + remainder n = n // 10 return reversed_number num = 12345 print(reverse_number(num)) # Output: 54321
1. The function
reverse_number takes an integer
n as input.
2. It initializes a variable
reversed_number to 0, which will be used to store the reversed number.
3. The function then enters a
while loop, which will continue until
n is greater than 0.
4. Inside the loop, the remainder of
n when divided by 10 is calculated and stored in the variable
remainder. This will give us the last digit of
5. The value of
reversed_number is then updated to be the current value of
reversed_number multiplied by 10, plus the value of
remainder. This shifts the current digits of
reversed_number one place to the left and adds the value of
remainder at the end.
6. Finally, the value of
n is updated to be the integer division of
n by 10, which removes the last digit from
7. The loop continues until
n is 0, at which point the final value of
reversed_number is returned.
- Create a telegram bot step by step using python - June 2, 2023
- Easy way to create a database in MySQL - April 27, 2023
- 5 Unique Hackathon Project Ideas: Creative and Innovative - March 27, 2023