原题地址: https://leetcode-cn.com/problems/reverse-integer/
题目描述
整数反转
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−2^31 , 2^31 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
第一种解法思路:
使用字符串反转拼接的方法来实现整数反转
import java.util.Scanner;
public class 整数反转4 {
public static void main(String[] args) {
// 输入一个数字
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
// 返回反转后的数字
System.out.println(reverse(x));
sc.close();
}
public static int reverse(int x) {
// 将整数转换成字符串
String str = Integer.toString(x);
// 将字符串转换成字符数组
char[] num = str.toCharArray();
// 数组初始值下标
int minIndex = 0;
// 数组长度(最大下标)
int maxIndex = str.length();
// 用字符串缓冲类来拼接字符串
StringBuffer sBuffer = new StringBuffer();
// 查看这个数是不是复数,是就初始下标+1
if (num[0] == '-') {
minIndex++;
}
// 查看这个数最后位数是不是零,是就去掉,上限-1
while (num[--maxIndex] == '0' && maxIndex > 1) {
}
// 字符串的拼接
for (int i = maxIndex; i >= minIndex; i--) {
sBuffer.append(num[i]);
}
// 用try 查看是否报错,报错就说明将字符串转换后的数字超出整形界限 2^31-1(2147483647) 和 -2^31(-2147483648)
try {
// 查看初始值是否是零,来判断是否是复数
return minIndex == 0 ? Integer.valueOf(sBuffer.toString()) : -Integer.valueOf(sBuffer.toString());
} catch (Exception e) {
return 0;
}
}
}
然后发现字符串缓冲类里是提供的有reverse()这个字符串翻转的方法的……
public static int reverse(int x) {
String str = Integer.toString(x);
try {
if(str.charAt(0) == '-'){
return -Integer.valueOf(new StringBuffer(str.substring(1,str.length())).reverse().toString());
}else{
return Integer.valueOf(new StringBuffer(str).reverse().toString());
}
} catch (Exception e) {
return 0;
}
}
还可以这样
public static int reverse(int x) {
// 用长整形储存反转后的值
long n = 0;
while (x != 0) {
//n的第一位数就是x的最后一位数,依次循环,负数取余后仍是负数
n = n * 10 + x % 10;
x = x / 10;
}
// int整形范围为 −2^31 ~ 2^31−1 为 -2147483648 ~ 2147483647
//return (int) ((n<Integer.MAX_VALUE && n > Integer.MIN_VALUE)?n:0);
// 如果强行转换后的int整形数据与原long的数据不一致,则说明数据已经溢出超出int范围
return (int) n == n ? (int) n : 0;
}