本文共 1152 字,大约阅读时间需要 3 分钟。
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 注意: 假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。class Solution { public int reverse(int x) { int num = x;//数字存起来 if (num < 0) { x = Math.abs(num);//换成正整数计算 } if (x >= 0 && x < 10) { return x;//一位数,直接返回 } int numTmp = x; int count = 0; while (x > 0) { count++;//统计是几位数 x /= 10; } int[] arr = new int[count]; for (int i = 0; i < count; i++) { arr[i] = numTmp % 10;//把每一位从个位开始放在一个数组里 numTmp /= 10; } long res = 0;//计算中可能会溢出,因此设为long for (int i = 0, j = count - 1; i < count; i++, j--) { res += arr[i] * (long) Math.pow(10, j); if (res>(long)Math.pow(2,31)-1){//如果溢出,则将结果设为0,跳出循环。 res=0; break; } } if (num >= 0) { return (int)res;//数为正整数 }else { return -(int)res;//数为负整数 } }}
原文:https://blog.csdn.net/qq_40408483/article/details/89025284