您的位置:首页 > 其它

Leetcode-reverse-integer

2016-06-26 16:29 435 查看


题目描述

Reverse digits of an integer.

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

click to show spoilers.
Have you thought about this?

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

leetcode上的题目就是各种限制条件多,注意下方的那些提示,有些方法是不能用的。

public class Solution {
public int reverse(int x) {
boolean isfu = false;
if(x == 0)
return 0;
if(x < 0){
x = Math.abs(x);
isfu = true;
}

String str = String.valueOf(x);
char[] charArray = str.toCharArray();
int n = charArray.length;
for(int i=0; i<n/2; i++){
char temp = charArray[i];
charArray[i] = charArray[n-1-i];
charArray[n-1-i] = temp;
}
String res = "";
int j = 0;
for(int i=0; i<n; i++){
if(charArray[i] != '0'){
break;
}
j++;
}
for(int i=j; i<n; i++){
res += charArray[i];
}
int s = Integer.parseInt(res);
if(isfu){
return 0-s;
}else{
return s;
}
}
}首先:是负数的标记出来,并转为正数处理。

其次,倒置处理结束后,寻找到第一个不是0的位置,把该位置后面的所有的数字全部输出出来即可。

最后,如果是负数,则加上符号,不是则输出上述结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: