# Reverse a Number

Page 1 of 1

## 3 Replies - 11669 Views - Last Post: 07 August 2007 - 08:48 PM

### #1 mitra_pvsm

• New D.I.C Head

Reputation: 0
• Posts: 2
• Joined: 07-August 07

# Reverse a Number

Posted 07 August 2007 - 12:50 AM

Hi,

I was trying to reverse a number by accepting from the user but unable to do so as its going to infinity with the condition I'm checking. Could somone please help me with this.

I'm using the following code.

```print("Enter a Number : ");
\$n=<stdin>;
\$s=0;
while(\$n>0)
{
\$s=(\$s*10)+(\$n%10);
\$n=\$n/10;
print("S: \$s - N: \$n\n");
}
print("Reverse : \$s\n");

```

- Mitra.

Is This A Good Question/Topic? 0

## Replies To: Reverse a Number

### #2 PsychoCoder

Reputation: 1649
• Posts: 19,853
• Joined: 26-July 07

## Re: Reverse a Number

Posted 07 August 2007 - 12:55 AM

Are you using Perl or Python?

### #3 mitra_pvsm

• New D.I.C Head

Reputation: 0
• Posts: 2
• Joined: 07-August 07

## Re: Reverse a Number

Posted 07 August 2007 - 01:01 AM

Hi,

I was using Perl. However, I got the output but please confirm whether the procedure followed by me is correct or not.

```print("Enter a Number : ");
\$n=<stdin>; chop(\$n);
\$s=\$r=0;
while(\$n>0)
{
\$r=(\$n%10);
\$s=(\$s*10)+\$r;
chop(\$n);
print("R: \$r - S: \$s - N: \$n\n");
}
print("Reverse : \$s\n");

```

• D.I.C Regular

Reputation: 27
• Posts: 401
• Joined: 23-January 07

## Re: Reverse a Number

Posted 07 August 2007 - 08:48 PM

<stdin> should really be <STDIN> and chop() should be chomp().

Besides that, unless you are constrained by some requirements to reverse the number without using the reverse() operator, it can simply be done like this:

print "Enter a Number : ";
chomp(my \$n = <STDIN>);
\$n = reverse \$n;
print \$n;

is this school/class work?