How to reverse an integer in Python 3.

In Python 3 int type is the same as long so there is no need to check for int overflow.

In other cases you will have to check for integer max value and min value to avoid a stack overflow.

The steps are bellow with each testing step shown for reversing 125 into 521.

Using modulus operator to find the remainder after dividing by 10

remainder = n % 10

if n = 125

steps:

1: 125 % 10 = 5 2: 12 % 10 = 2 3: 1 % 10 = 1

Next we multiply rev by 10 to move to the next digit. For first digit it’s 5

rev = rev * 10 + remainder

steps:

1: (0*10)+5 = 5 2: (5*10)+2 = 52 3: (52*10)+1 = 521

next is we round down the result of n / 10 and move to the next digit.

n = math.floor(n / 10)

steps:

1: 125/10 = floor(12.5) = 12 2: 12/10 = floor(1.2) = 1 3: 1/10 = floor(0.1) = 0 END

Whole Python script to try.

import math # Python3 program to reverse a number here int is the same as long - no int limit n = 98743222222 rev = 0 while(n > 0): remainder = n % 10 # n mod 10 for remainder rev = rev * 10 + remainder # add it to reversed n = math.floor(n / 10) # divide n by 10 to move to the next step, must round down here print(rev) #see each step if you like print(n) print(rev)

Or try this version that works with negative numbers also.

import math # Python3 program to reverse a number here int is the same as long - no int limit # This version works with negative numbers too: n = 98743 rev = 0 isnegative = False if (n < 0): isnegative = True n = abs(n) while(n > 0): remainder = n % 10 # n mod 10 for remainder rev = rev * 10 + remainder # add it to reversed n = math.floor(n / 10) # divide n by 10 to move to the next step, must round down here print(rev) #see each step if you like if isnegative: rev = rev * -1 print(rev)

## Leave a Reply