Reputation: 621
I'm trying to reverse random int in JavaScript. I'm using this code:
'use strict';
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
print(reverse_a_number(+gets())); //**+gets()** is like scanner.nextInt in Java and **print();** work's like console.log(); in JS.
This work well if number are not a big integer.
For the first test in my judge, code works correctly:
Input Output
256 652
123.45 54.321
But for BI i get Wrong Answer:
Maybe the best way is to cast array to string... Any suggestions?
Upvotes: 0
Views: 501
Reputation: 7
function reverseNum(n){
var reverse = 0
while(n!=0) {
var rem = n%10
reverse = reverse*10 +rem
n = parseInt(n/10)
}
return reverse
}
reverseNum(523)
Upvotes: 0
Reputation: 2462
The reason is that you cast your get()
input to number. Don't do this, use a string as, I think, you receive it. Example:
'use strict';
function gets() {
return '52387456983765.98364593786'
}
function reverse_a_number(n)
{
n = n + '';
return n.split('').reverse().join('');
}
console.log(reverse_a_number(+gets())); // "489.56738965478325"
function reverse_a_number_new(n)
{
return n.split('').reverse().join('');
}
console.log(reverse_a_number_new(gets())); // "68739546389.56738965478325"
To read more about floats in JS: https://javascript.info/number#imprecise-calculations
Upvotes: 2