JavaScript: How to reverse a number?
Matthew Martinez
Below is my source code to reverse (as in a mirror) the given number. I need to reverse the number using the reverse method of arrays.
<script> var a = prompt("Enter a value"); var b, sum = 0; var z = a; while(a > 0) { b = a % 10; sum = sum * 10 + b; a = parseInt(a / 10); } alert(sum);
</script> 3 18 Answers
Low-level integer numbers reversing:
function flipInt(n){ var digit, result = 0 while( n ){ digit = n % 10 // Get right-most digit. Ex. 123/10 → 12.3 → 3 result = (result * 10) + digit // Ex. 123 → 1230 + 4 → 1234 n = n/10|0 // Remove right-most digit. Ex. 123 → 12.3 → 12 } return result
}
// Usage:
alert( "Reversed number: " + flipInt( +prompt("Enter a value") )
)The above code uses bitwise operators for quick math
This method is MUCH FASTER than other methods which convert the number to an Array and then reverse it and join it again. This is a low-level blazing-fast solution.
Illustration table:
const delay = (ms = 1000) => new Promise(res => setTimeout(res, ms))
const table = document.querySelector('tbody')
async function printLine(s1, s2, op){ table.innerHTML += `<tr> <td>${s1}</td> <td>${s2||''}</td> </tr>`
}
async function steps(){ printLine(123) await delay() printLine('12.3 →') await delay() printLine(12, 3) await delay() printLine('1.2', '3 × 10') await delay() printLine('1.2 →', 30) await delay() printLine(1, 32) await delay() printLine(1, '32 × 10') await delay() printLine('1 →', 320) await delay() printLine('', 321) await delay()
}
steps()table{ width: 200px; }
td { border: 1px dotted #999;
}<table> <thead> <tr> <th>Current</th> <th>Output</th> </tr> </thead> <tbody> </tbody>
</table> 5 Assuming @DominicTobias is correct, you can use this:
console.log( +prompt("Enter a value").split("").reverse().join("")
) 4 I was recently asked how to solve this problem and this was my initial solution:
The desired output: 123 => 321, -15 => -51, 500 => 5
function revInt(num) {
// Use toString() to convert it into a String
// Use the split() method to return a new array: -123 => ['-', '1','2','3']
// Use the reverse() method to reverse the new created array: ['-', '1','2','3'] => ['3','2','1','-'];
// Use the join() method to join all elements of the array into a string let val = num.toString().split('').reverse().join(''); // If the entered number was negative, then that '-' would be the last character in // our newly created String, but we don't want that, instead what we want is // for it to be the first one. So, this was the solution from the top of my head.
// The endsWith() method determines whether a string ends with the characters of a specified string if (val.endsWith('-')) { val = '-' + val; return parseInt(val); } return parseInt(val);
}
console.log(revInt(-123));A way better solution:
After I gave it some more thought, I came up with the following:
// Here we're converting the result of the same functions used in the above example to
// an Integer and multiplying it by the value returned from the Math.sign() function.
// NOTE: The Math.sign() function returns either a positive or negative +/- 1,
// indicating the sign of a number passed into the argument.
function reverseInt(n) { return parseInt(n.toString().split('').reverse().join('')) * Math.sign(n)
}
console.log(reverseInt(-123));NOTE: The 2nd solution is much more straightforward, IMHO
1This is my solution, pure JS without predefined functions.
function reverseNum(number) { var result = 0, counter = 0; for (i = number; i >= 1; i = i / 10 - (i % 10) * 0.1) { counter = i % 10; result = result * 10 + counter; } return result;
}
console.log(reverseNum(547793)); Or, as a one-liner ( x contains the integer number to be inversed):
revX=x.toFixed(0).split('').reverse().join('')-0;The number will be separated into its individual digits, reversed and then reassembled again into a string. The -0 then converts it into a number again.
Firstly, I don't think you are using an array to store the number. You are using a java script variable.
Try out this code and see if it works.
var a = prompt("Enter a value");
var z = a;
var reverse = 0;
while(z > 0)
{ var digit = z % 10; reverse = (reverse * 10) + digit; z = parseInt(z / 10);
}
alert("reverse = " + reverse); Explanation
Using the JavaScript reverse() array method you can reverse the order of the array elements.
Code
var a = prompt("Enter a value");
var arr = [];
for (var i = 0; i < a.length; i++) { arr[i] = a.charAt(i);
}
arr.reverse();
alert(arr); Assuming you may want to reverse it as a true number and not a string try the following:
function reverseNumber(num){ num = num + ''; let reversedText = num.split('').reverse().join(''); let reversedNumber = parseInt(reversedText, 10); console.log("reversed number: ", reversedNumber); return reversedNumber; } Using JavaScript reverse() and Math.sign() you can reverse a number both positive and negative numbers.
var enteredNum = prompt("Enter integer");
function reverseInteger(enteredNum) { const reveredNumber = enteredNum.toString().split('').reverse().join(''); return parseInt(reveredNumber)*Math.sign(enteredNum);
}
alert(reverseInteger(enteredNum)); function add( num:number){ //159
let d : number;
let a : number =0;
while(num > 0){ //159 15 1 d = num % 10; a = a * 10 + d; //9 95 951 num = Math.floor(num/10); // 15 1 0
} return a; //951
}
console.log(add(159)); 1 Reversing a number without converting it into the string using the recursive approach.
const num = 4578;
const by10 = (num) => { return Math.floor(num / 10);
};
const remBy10 = (num) => { return Math.floor(num % 10);
};
const reverseNum = (num, str = "") => { if (num.toString().length == 1) return (str += num); return reverseNum(by10(num), (str += remBy10(num)));
};
console.log(reverseNum(num, "")); The simplest solution is to reverse any integer in js. Doesn't work with float.
const i2a = number.toString().split("");
const a2i = parseInt(i2a.reverse().join(""));
console.log(a2i); Apply logic of reversing number in paper and try, and you have to care about dividing because it gives float values. That's why we have to use parseInt().
function palindrome()
{ var a = document.getElementById('str').value; var r=0 ,t=0; while(a>0){ r=a%10; t=t*10+r; a=parseInt(a/10); } document.write(t);
}<form> <input type="text"/> <input type="submit" onClick="palindrome()" />
<form> var reverse = function(x) { if (x > 2147483647 || x < -2147483648 || x === 0) { return 0; } let isNegative = false; if(x < 0){ isNegative = true; x = -x; } const length = parseInt(Math.log10(x)); let final = 0; let digit = x; let mul = 0; for(let i = length ; i >= 0; i--){ digit = parseInt(x / (10**i)); mul = 10**(length-i); final = final + digit * mul; x = parseInt(x % 10**i); } if (final > 2147483647 || final < -2147483648 ) { return 0; } if(isNegative){ return -final; } else{ return final; }
};
console.log(reverse(1534236469));
console.log(reverse(-123));
console.log(reverse(120));
console.log(reverse(0));
console.log(reverse(2,147,483,648)); Sweet and simple:
function reverseNumber(num){ return parseInt(num.toString().split("").reverse().join(""));
} 1 The above code will not work for negative numbers. Instead, use the following:
/** * @param {number} x * @return {boolean} */
var isPalindrome = function(x) { return ((x>=0) ? ((x==(x = parseInt(x.toString().split("").reverse().join("")))) ? true:false) : false);
}; The simplest way is to
- Covert it into a string and apply the
reverse()method - Change it back to number
- Check for the value provided if negative or positive with Math.sign()
Below is my solution to that.
function reverseInt(n) { const reversed = n.toString().split('').reverse().join(''); return parseInt(reversed) * Math.sign(n);
}
console.log(reverseInt(12345)); My solution to reverse a string:
var text = ""
var i = 0
var array = ["1", "2", "3"]
var number = array.length
var arrayFinal = []
for (i = 0; i < array.length; i++) { text = array[number - 1] arrayFinal.push(text) text = "" number = number - 1
}
console.log(arrayFinal)