Find the reverse of a number in the way that the number hundred place number should be in the unit place in Python. [Eg: 1234 should print as 4312]

Question:

code 1

I am getting output as 4321 but it should print 4312 in Python

code 2

Asked By: MLS Mahesh

||

Answers:

This code reverses a number. you want to create a new digit such that:

….+10b+a -> ….+10a+b

so you should subtract result from 9b-9a :

def reverse(n):
    x = int(0)
    while(n>0):
        x=x*10 + n%10
        print(x)
        n=int(n/10)
    return x

n=1234;
print(n)
n = reverse(n)
print(n)
a = int(n % 10);
b = int(((n % 100) - a) / 10)
print(n-9*b+9*a)
Answered By: morteza

This method may help:

n = 1234
rev = list(reversed(str(n)))
rev[-1], rev[-2] = rev[-2], rev[-1]
rev = int("".join(rev))

Edit: replacement of [0] and [1] to [-1] and [-2] as per @zwitsch’s recomendation

Answered By: user17301834

to remain in your philosophy, it would be enough to stop the loop as soon as n drops below 100 then append n to rev:

n = 1234
rev = 0

while n > 100:
    a = n % 10
    rev = rev * 10 + a
    n = n // 10

rev = rev*100 + n

print(rev)  // 4312
Answered By: zwitsch
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.