Welcome to Dream.In.Code
Become an Expert!

Join 149,505 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,335 people online right now. Registration is fast and FREE... Join Now!




Reverse a Number

 
Reply to this topicStart new topic

Reverse a Number

mitra_pvsm
6 Aug, 2007 - 11:50 PM
Post #1

New D.I.C Head
*

Joined: 6 Aug, 2007
Posts: 2


My Contributions
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.

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.
User is offlineProfile CardPM
+Quote Post

PsychoCoder
RE: Reverse A Number
6 Aug, 2007 - 11:55 PM
Post #2

using DIC.Core;
Group Icon

Joined: 26 Jul, 2007
Posts: 9,481



Thanked: 161 times
Dream Kudos: 9050
Expert In: VB, VB.Net, C#, SQL, ASP, ASP.Net, Web Development, HTML, CSS, Win32 API, Javascript, mySQL, J#, Boo.Net

My Contributions
Are you using Perl or Python?
User is online!Profile CardPM
+Quote Post

mitra_pvsm
RE: Reverse A Number
7 Aug, 2007 - 12:01 AM
Post #3

New D.I.C Head
*

Joined: 6 Aug, 2007
Posts: 2


My Contributions
Hi,

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

CODE

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



User is offlineProfile CardPM
+Quote Post

KevinADC
RE: Reverse A Number
7 Aug, 2007 - 07:48 PM
Post #4

D.I.C Head
Group Icon

Joined: 23 Jan, 2007
Posts: 238



Thanked: 6 times
Dream Kudos: 50
My Contributions
<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?
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 06:55PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Help!

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month