Description
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 230]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Examples
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
解题思路
比较容易想到的方法就是用java自带的各种API进行操作
- 记录数字正负,然后转换成正数
- 把数字通过toString转换成字符串
- 通过字符串的reverse进行反转
- 把反转之后的字符串用Integer.parseInt转换成int型数字进行返回
具体Java代码如下:
class Solution {
public int reverse(int x) {
int flag = x > 0? 1: -1;
Integer x1 = x * flag;
String str = x1.toString();
str = new StringBuffer(str).reverse().toString();
try{
x1 = flag * Integer.parseInt(str);
}catch(Exception e){
x1 = 0;
}
flag = x1;
return flag;
}
}
其他
- 其实题目不难,但是要注意审题啊审题!题目里提到了可能出现反转之后int溢出的情况,出现了这种情况的话就返回0,所以最后用try catch抓了下溢出的错直接在操作里赋0了
- 字符串的reverse操作是针对StringBuffer的,但是StringBuffer和String的转换非常方便,Stringbuffer sb = new Stringbuffer(str),String str = sb.toString()
- 其他没有什么了,继续刷刷刷!