7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.
public class Test7 {
public static void main(String[] args){
Test7 test = new Test7();
System.out.print(test.reverse(-10));
}
public int reverse(int x) {
try{
int index = 0;
if(x<0){
index = 1;
}
String s = String.valueOf(x);
char[] c = s.toCharArray();
int last = s.length()-1;
for(int i=index,j=last;i<=j;i++,j--){
char temp = c[i];
c[i] = c[j];
c[j] = temp;
}
return new Integer(Integer.parseInt(new String(c)));
}catch(NumberFormatException e){
return 0;
}
}
}