Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Java:
public class Solution {
public int reverse(int x) {
String s = Integer.toString(x);
Boolean isMinus = false;
if(x < 0)
{
isMinus = true;
s = s.substring(1);
}
char[] sarray = s.toCharArray();
for(int i=0; i<s.length()/2; i++)
{
char temp = sarray[i];
sarray[i] = sarray[s.length()-1-i];
sarray[s.length()-1-i] = temp;
}
String b = new String(sarray);
if(sarray.length == 10)
{
long l = Long.parseLong(b);
if(l > 2147483647) return 0;
}
int k = Integer.parseInt(b);
return isMinus? -k:k;
}
}