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:
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[-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
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
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[-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
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