Javascipt version
Javascript have the function that reverse the String, so it is pretty easy to do in js.
1 2 3 4 5 6 7 8 9
|
var reverse = function(x) { var y = parseInt(x.toString().split('').reverse().join('')) if (y >= 2**31-1 || -y <= -(2**31)) return 0; return x < 0 ? -y : y }
|
Java version
This java version is not prefect through, I have not handle the overflow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Solution { public static int reverse(int x) { int result = 0; if(x == 10){return 1;} while (x!=0){ int tail = x % 10; int newResult = result * 10 + tail; result =newResult; x = x /10; } return result; } public static void main(String[] args){ System.out.print(reverse(123)); } }
|