给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231, 231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
class Solution {
public int reverse(int x) {
long result = 0;
int y=0,z=0;
z=Math.abs(x);
while(z > 0){
z=z/10;
y++;
}
z=Math.abs(x);
int num[] = new int[y];
for(int i=0;z>0;i++){
num[i] = z%10;
z = z/10;
}
for(int i=0;i<num.length;i++){
result = result*10+num[i];
}
if(result > (Math.pow(2,31)-1) || result < Math.pow(-2,31)){
result = 0;
}
if(x > 0){
return (int)result;
}else{
return (int)result*-1;
}
}
}
审题:要求将一个int取值范围内的数反转,如果不溢出返回该数,如果溢出返回0
解题思路:将传进来的数的绝对值,进行连续除10,算出来它一共有多少位,创建一个长度等于其位数的数组。然后对10求余并将余数存在数组中,再除10直到该数等于0。将数组中的数,在循环乘10组合起来。判断原数是不是负数,选择性给结果是否加负号,并进行返回。
优化后的版本
class Solution {
public int reverse(int x) {
long result = 0;
int y=0,z=0;
z=Math.abs(x);
while(z > 0){
y = z%10;
z = z/10;
result = result*10+y;
}
if(result > (Math.pow(2,31)-1) || result < Math.pow(-2,31)){
result = 0;
}
if(x > 0){
return (int)result;
}else{
return (int)result*-1;
}
}
}
再次优化后的版本
class Solution {
public int reverse(int x) {
long result = 0;
int y=0;
while(x > 0 || x < 0){
y = x%10;
x = x/10;
result = result*10+y;
}
if(result > (Math.pow(2,31)-1) || result < Math.pow(-2,31)){
result = 0;
}
return (int)result;
}
}