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]

Viewed 26

code 1

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

code 2

3 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)

This method may help:

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

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
Related