+ 1
How to reverse a number in a FOR loop
Hi guys, I have something that is driving me insane. I am trying to reverse a number. I can reverse a string, no problem, but when it comes to a number I keep getting 0 or undefined, no matter what, and I don't understand why. I would appreciate it if someone can look at my code, and give an explanation too, please. I need to master Javascript but I struggle a lot and I do spend a lot of time on it. Thanks in advance. function reverse(num){ var reversedNum = 0; for(var i = num.length - 1; i >= 0; i--){ reversedNum = reversedNum + num[i]; } return reversedNum; } console.log(reverse(1234));
6 Answers
+ 13
Your algorithm works fine for reversing a string input if starting with an empty string. However it didn't work well for numbers since you're treating the input as string by using index inside the for loop.
Therefore if you want to preserve the same algorithm then converting the number to string will do the job. đ
Something like reverse(1234.toString())
+ 13
//Try this.
function reverse(num){
num+=""
var reversedNum = "";
for(var i = num.length - 1; i >= 0; i--){
reversedNum = reversedNum + num[i];
}
return reversedNum;
}
console.log(reverse(1234));
+ 8
// This uses string to get reversedNum
function reverse(num){
var reversedNum = 0;
var snum = num.toString();
var len = snum.length - 1;
for(var i = len; i >= 0; i--){
reversedNum += parseInt(snum[i]) * Math.pow(10, i);
}
return reversedNum;
}
// This doesn't use string, however we need
// a temporary array to store the digits.
// Not so compact, but no string used : )
// Based on @Dan Walker's suggestion.
function reverse2(num){
var rem = 0, digits = 0;
var tmp = [];
// Collect the digits in reverse,
// by adding them in temporary array
while (num != 0){
rem = parseInt(num % 10);
num = parseInt(num / 10);
tmp.push(rem);
digits++;
}
var reversedNum = 0, exp = digits;
for(var i = 0; i < digits; i++)
{
reversedNum += parseInt(tmp[i]) * Math.pow(10, --exp);
}
return reversedNum;
}
console.log(reverse(1234));
console.log(reverse2(1234));
+ 5
Hint:
number mod 10 (%) gives you the last digit
number / 10 (with integer division) gives you the other digits. You can use parseInt or Math.floor to get the integer part of the division.
It's a great exercise, I've seen that it is sometimes used as an interview question for grad jobs, but they specifically request no strings!
+ 2
Thanks everyone - I did not want to use strings, so my final code is now with the correct output:
function reverse(num){
var reversedNum = 0;
for(var i = num.length - 1; i >= 0; i--){
reversedNum = reversedNum + num[i];
}
return parseInt(reversedNum);
}
console.log(reverse((1234).toString()));
Feel free to suggest improvements :)