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

#1 mitra_pvsm  Icon User is offline

  • New D.I.C Head

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

Reverse a Number

Post icon  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");




Thanks in advance.

- Mitra.

Is This A Good Question/Topic? 0
  • +

Replies To: Reverse a Number

#2 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1638
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Re: Reverse a Number

Posted 07 August 2007 - 12:55 AM

Are you using Perl or Python?
Was This Post Helpful? 0
  • +
  • -

#3 mitra_pvsm  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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");



Was This Post Helpful? 0
  • +
  • -

#4 KevinADC  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • 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?
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1