LeetCode--007--整数反转(java)

时间:2023-03-09 06:28:46
LeetCode--007--整数反转(java)

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

 示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

解法烂的一批,直接看第二个吧

 class Solution {
public int reverse(int x) {
boolean isNeg = false;
if(x<0){
x = Math.abs(x);
isNeg = true;
}
String s = String.valueOf(x);
Stack<Character> stack= new Stack();
for(int i=0;i<s.length();i++){
stack.push(s.charAt(i));
}
s="";
while(!stack.isEmpty()){
s+=stack.pop();
}
int res=0;
try{
res = Integer.parseInt(s);
}catch(Exception e){
System.out.println(0);
return 0;
} if(isNeg){
res = -1 * res;
}
System.out.println(res);
return res;
}
}

方法2:

int from -2147483648 to 2147483647

为了避免反转越界,指定res为long类型。

 class Solution {
public int reverse(int x) {
long res = 0;
while(x != 0){
res = res * 10 + x % 10;
x = x / 10;
if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
}
return (int)res;
}
}

相关文章