1 Star 0 Fork 0

临窗旋墨 / basics

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
J0007_E_Reverse.java 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
package pers.vic.basics.leetcode;
/**
* @author Vic.xu
* @description:7. 整数反转 \
* 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
* 注意:
* <p>
* 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
* @date: 2020/11/2 10:54
*/
public class J0007_E_Reverse {
/**
* 从高位开始一个个反转吧
* 1 2 3 4 5 6 → 6 5 4 3 2 1
* 先除10 取余数 得到最后一位,取倒数第二位的时候,把之前取得的结果乘以10 然后加上当前结果(如此遍历即可),从后往前一步步得出结果
* -2147483648 < y < 2147483647
*/
public static int reverse(int x) {
int y = 0;
while (x != 0) {
int z = x % 10;
x = x / 10;
//判断是否溢出
if (y > Integer.MAX_VALUE / 10 || (y == Integer.MAX_VALUE / 10 && y > 7)) {
return 0;
}
if (y < Integer.MIN_VALUE / 10 || (y == Integer.MIN_VALUE / 10 && y < -8)) {
return 0;
}
y = y * 10 + z;
}
return y;
}
public static int reverse2(int x) {
boolean negative = x < 0;
long res = 0;
if (negative) {
res = 0 - Long.valueOf(new StringBuilder(String.valueOf(x).substring(1)).reverse().toString());
} else {
res = Long.valueOf(new StringBuilder(String.valueOf(x)).reverse().toString());
}
return (int) res == res ? (int) res : 0;
}
public static void main(String[] args) {
System.out.println(reverse(-123));
}
}
Java
1
https://gitee.com/xuqiudong/basics.git
git@gitee.com:xuqiudong/basics.git
xuqiudong
basics
basics
master

搜索帮助