Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Faith Mueni Kilonzi
Faith Mueni Kilonzi

Posted on

     

The reverse of a number using python

Given a number, reverse its digits and print the new number.
For example:
Input : num = 8972
Output: 2798

There are a couple of ways to solve this:

1. Reverse Number using String slicing

We convert the given number to string using str()
Reverse it using string slicing
Convert the reversed string to int and return the int.

defreverseNumber(n):reversed_number=int(str(n)[::-1])returnreversed_number
Enter fullscreen modeExit fullscreen mode

2. Reverse Number using While Loop

Using a while loop, iterate through the list of the digits from the last one and append the digits into a new number.

defreverseNumber(n):reversed_number=0while(n!=0):r=int(n%10)reversed_number=reversed_number*10+rn=int(n/10)returnreversed_number
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a full-stack software engineer, technical writer, and DevOps enthusiast, with a passion for problem-solving through implementation of high-quality software products.I hold a bachelor’s degree
  • Location
    Nairobi, Kenya
  • Education
    BSc. Computer Science, Ashesi University
  • Work
    Software Engineer and Technical Writer
  • Joined

More fromFaith Mueni Kilonzi

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp