# reverse a number using javascript

Page 1 of 1

## 4 Replies - 99476 Views - Last Post: 23 December 2007 - 05:46 AM

### #1 rpavithra

Reputation: 0
• Posts: 1
• Joined: 26-November 07

# reverse a number using javascript

Posted 26 November 2007 - 05:25 AM

got to reverse a no inputed by the user.well,the code that i tried is as follows:
<html>
<script language="javascript">
var a,b;
a=parseInt(prompt("enter a no."));
while(a>0)
{
b=a % 10;
a=parseInt(a/10);
}
document.write(b+a)
</script>
</html>
Is This A Good Question/Topic? 0

## Replies To: reverse a number using javascript

### #2 beef

Reputation: 1
• Posts: 141
• Joined: 02-November 06

## Re: reverse a number using javascript

Posted 26 November 2007 - 10:32 AM

rpavithra, on 26 Nov, 2007 - 06:25 AM, said:

got to reverse a no inputed by the user.well,the code that i tried is as follows:
<html>
<script language="javascript">
var a,b;
a=parseInt(prompt("enter a no."));
while(a>0)
{
b=a % 10;
a=parseInt(a/10);
}
document.write(b+a)
</script>
</html>

It's overwriting b each time it loops through so all you're ending up with is the last digit. Try moving your document.write up inside your loop.

### #3 xenofied

Reputation: 0
• Posts: 1
• Joined: 30-July 06

## Re: reverse a number using javascript

Posted 14 December 2007 - 05:47 PM

Hereunder is a solution for your perusal. Albeit the code as a bug, it should still serve as a quick reference to better help clarify how recursion works:

```<html>
<script language = "javascript">
//It's important to pre-assign b to a value
//before using it in the loop. In your case
//you'll need to set it to zero.

var a, b = 0;
a = parseInt(prompt("Enter number to reverse: "));

//The idea is to continually divide 'a' (resulting quotients) by 10;
//then multiply the remainders 'b' by 10, adding them to each
//other until there is no remainder left (i.e. b = zero).

while(a > 0)
{
b = b * 10
b = b + parseInt(a % 10)
a = parseInt(a / 10)
}
document.write("Reversed number: ", b)
</script>
</html>
```

BUG:When you precede a number with zero you get a wrong output from that which is desired. Anyway, i'll leave you with this piece and let you figure out what the problem is. Wherever you're stuck, feel free to ask questions. I am sure someone will definitely respond. Have fun

This post has been edited by xenofied: 14 December 2007 - 05:57 PM

### #4 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 187
• Posts: 4,673
• Joined: 26-November 04

## Re: reverse a number using javascript

Posted 23 December 2007 - 03:12 AM

Moved to Javascript Forums.

Reputation:

## Re: reverse a number using javascript

Posted 23 December 2007 - 05:46 AM

There goes the neighborhood
```String.prototype.reverse = function() {
return this.split('').reverse().join('');
};
var n = 1234;