您的位置:首页 > 其它

LeetCode 算法刷题(7)

2017-03-22 13:27 134 查看
7. Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 leecode