Leetcode: Reverse Integer

本文深入探讨了整数反转算法的核心实现,包括如何处理末尾为0的情况及整数溢出的问题。详细解释了算法逻辑,并提供了优化处理边界情况的方法,确保算法在不同场景下都能正确运行。
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

一次通过,它的spoiler里面的提示有两个:

1. 末尾为0的情况,这个考虑到了

2. Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

最新的题目要求已经改成 assume that your function returns 0 when the reversed integer overflows. 简化了,

 1 public class Solution {
 2     public int reverse(int x) {
 3         boolean isNeg = false;
 4         if (x == 0) return x;
 5         if (x < 0) {
 6             isNeg = true;
 7             x = Math.abs(x);
 8         }
 9         int res = 0;
10         while (x != 0) {
11             int digit = x % 10;
12             x = x / 10;
13             if (res > (Integer.MAX_VALUE - digit) / 10) {
14                 return 0;
15             }
16             res = res * 10 + digit;
17         }
18         return isNeg? -res : res;
19     }
20 }

之前的题目没有设置overflow的test case,我们的处理是正数overflow就return Integer.MAX_VALUE,负数overflow就return Integer.MIN_VALUE. 参见下面Code Ganker的code。为了后面方便处理,先将数字转为正数。注意Integer.MIN_VALUE的绝对值是比Integer.MAX_VALUE大1的,所以经常要单独处理。如果不先转为正数也可以,只是在后面要对符号进行一下判断。这种题目考察的就是数字的基本处理,面试的时候尽量不能错,而且对于corner case要尽量进行考虑,一般来说都是面试的第一道门槛。

Signed Long Integer有32位,其中最高位用来做符号位,剩下31位来做无符号的数值,表值范围是(0  -  2^30+2^29+2^28+...+2^1+2^0)即(0 - 2^31-1)即0 to 2147483647。 加上符号位,范围是–2147483648 to 2147483647

推荐做法:


 
1
public int reverse(int x) { 2 if(x==Integer.MIN_VALUE) 3 return Integer.MIN_VALUE; 4 int num = Math.abs(x); 5 int res = 0; 6 while(num!=0) 7 { 8 if(res>(Integer.MAX_VALUE-num%10)/10) 9 return x>0?Integer.MAX_VALUE:Integer.MIN_VALUE; 10 res = res*10+num%10; 11 num /= 10; 12 } 13 return x>0?res:-res; 14 }

转载于:https://www.cnblogs.com/EdwardLiu/p/3710643.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值