[Tutor] reverse a number (was no subject)
Chris Kassopulo
ckasso@sprynet.com
Fri, 9 Aug 2002 21:12:15 -0400
On Fri, 9 Aug 2002 17:39:48 +0530
"Anand Ramakrishna" <anandrs@hexaware.com> wrote:
> Hi,
> I am having a strange problem with my python code for reversing a
> number. I tried it on a few combinations and works fine with most
> of them except when the number starts in '1'. If I give input as
> 123 it reverses and displays as 442. If I give input as 12 it
> reverses and displays as 12. Where as if I give any other number,
> it reverses properly and displays the correct result. The code is
> pasted below.
>
>
>
> print 'This program accepts a number and then reverses it'
> number = int(raw_input("Enter a number = "))
> temp_var = 0
>
> while (number/10) > 1 :
> temp_var = (temp_var*10) + (number%10)
> number = number/10
> else:
> temp_var = (temp_var*10) + number
> print 'The reversed number is ', temp_var
>
>
Greetings,
Ahem, sorry about the last mail.
To do this without using a string I had to loop through
the number twice. The first time to see how many digits,
the second to actually compute the number.
It's mighty ugly, but it works. There must be a better
way.
__________________________________________________________
print 'This program accepts a number and then reverses it'
userInput = int(raw_input("Enter a number = "))
# initialize variables
tempVar = 0
i = 0
# determine number of digits
number = userInput
while number >= 10:
number = number/10
i += 1
# compute reversed number
number = userInput
while number >= 10:
tempVar = tempVar + (number%10)*10**i
print (number%10)*10**i
number = number/10
i -= 1
else:
print (number%10)*10**i
number = tempVar + number
print 'The reversed number is', number
__________________________________________________________
Chris Kassopulo _/\_ Linux User #199893 _/\_ Slackware