给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231, 231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
提示:
-231 <= x <= 231 - 1
解题要点
懒得考虑了,就用最粗暴的倒序
public class Test7 {
/**
* 用最粗暴的方法解决
* 执行结果:通过显示详情添加备注执行用时:12 ms, 在所有 Java 提交中击败了5.60%的用户内存消耗:36.4 MB, 在所有 Java 提交中击败了5.01%的用户
* @param x
* @return
*/
public int reverse(int x) {
//先判断是否是-
String f="";
if(x<0) {
f="-";
}
int result = 0;
//1、将x转换成字符串
String str = x+"";
if("-".equals(f)) {
str =str.substring(1, str.length());
}
//2、倒序输出
StringBuffer bf = new StringBuffer();
boolean flag = true;//默认前面没有0
for (int i = str.length()-1; i >=0 ;i--) {
char now = str.charAt(i);
if(now=='0') {
if(flag) {
continue;
}
}else {
if(true) {
flag=false;
}
}
bf.append(now+"");
}
try {
String r = f+bf.toString();
//判断最后一位是不是-
result = Integer.parseInt(r);
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
public static void main(String[] args) {
// //按周期来计算
System.out.println(new Test7().reverse(-12300));
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer