LeetCode Top Interview Questions 7. Reverse Integer (Java版; Easy)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6


​welcome to my blog​

LeetCode Top Interview Questions 7. Reverse Integer (Java版; Easy)

题目描述

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

第一次做; 处理int类型溢出:检查到倒数第二位

class Solution {
public int reverse(int x) {
int res = 0;
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
while(x!=0){
res = res*10 + x%10;
//update
x=x/10;
//溢出检查; 放在update之后, 因为用到了update之后的x
//处理正数异常
if(x!=0 && res>max/10)
return 0;
//处理正数异常
if(x!=0 && res==max/10 && x%10>max%10)
return 0;
//处理负数异常
if(x!=0 && res<min/10)
return 0;
//处理负数异常
if(x!=0 && res==min/10 && x%10<min%10)
return 0;
}
return res;
}
}

第一次做;难点:处理int类型溢出; 要总结处一套处理数字异常的方法论:检查到倒数第二位

/*
-2^31 = -2,147,483,648
2^31-1 = 2,147,483,647

*/
class Solution {
public int reverse(int x) {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
int flag = x > 0?1:-1;
int[] arr = new int[10];
int index=0;
if(x==min)
return 0;
//统一按照正数形式处理
x = Math.abs(x);
while(x!=0){
arr[index] = x%10;
//update
x = x/10;
index++;
}
int res = 0;
for(int i=0; i<index; i++){
res = res*10 + arr[i];
//越界检查
if(flag>0){
if(i+1<index && res>max/10)
return 0;
if(i+1<index && res==max/100 && arr[i+1]>max%10)
return 0;
}
else{
if(i+1<index && -res<min/10)
return 0;
if(i+1<index && -res==min/10 && arr[i+1]>-(min%10))
return 0;
}
}
return flag*res;
}
}

​力扣最优解​​; 不用区分正负数, 直接计算即可; 我之所以统一成正数处理是因为我对负数的操作不熟悉

溢出条件有两个,一个是大于整数最大值MAX_VALUE,另一个是小于整数最小值MIN_VALUE,设当前计算结果为ans,下一位为pop。
从ans * 10 + pop > MAX_VALUE这个溢出条件来看

当出现 ans > MAX_VALUE / 10 且 还有pop需要添加 时,则一定溢出
当出现 ans == MAX_VALUE / 10 且 pop > 7 时,则一定溢出,7是2^31 - 1的个位数
从ans * 10 + pop < MIN_VALUE这个溢出条件来看

当出现 ans < MIN_VALUE / 10 且 还有pop需要添加 时,则一定溢出
当出现 ans == MIN_VALUE / 10 且 pop < -8 时,则一定溢出,8是-2^31的个位数
class Solution {
public int reverse(int x) {
int ans = 0;
while (x != 0) {
int pop = x % 10;
if (ans > Integer.MAX_VALUE / 10 || (ans == Integer.MAX_VALUE / 10 && pop > 7))
return 0;
if (ans < Integer.MIN_VALUE / 10 || (ans == Integer.MIN_VALUE / 10 && pop < -8))
return 0;
ans = ans * 10 + pop;
x /= 10;
}
return ans;
}
}


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java