7. Reverse Integer

Description:

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



Solution:


这是一道基本的对数字操作的题,除却简单外还需要注重细节,这道题就是注意 Integer的溢出问题。

1. 功能的实现: result = result * 10 + x % 10;

2. 溢出的检测:

a) The absolute value of Integer's minimum is larger 1 than Integer's maximum.

    To  the final answer, we need to judge its plus-minus. 

    For example,

return x?result:-result;

b) Even if the value of x  is less than the Integer's maximum, its reverse value will be larger than that. 

    We can judge it in the loop.

For example,

if (Math.abs(result) > Integer.MAX_VALUE / 10)

or 
int t = res * 10 + x % 10;
 if (t / 10 != res) return 0; // If the value has exceeded the limit, it divided by 10 will differ from before.


or a direct comparison

if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;

So, the code should be:

class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (abs(res) > INT_MAX / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};


class Solution {
public:
    int reverse(int x) {
        int res = 0;
        while (x != 0) {
            int t = res * 10 + x % 10;
            if (t / 10 != res) return 0;
            res = t;
            x /= 10;
        }
        return res;
    }
};


An easier implementation:

class Solution {
    public int reverse(int x) {
        long res = 0; // ***When res use the long type, it will keep the value to check whether it exceed the limit.
        while(x != 0) {
            int tail = x % 10;
            res = res * 10 + tail;
            if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
                return 0;
            }
            x = x / 10;
        }
        return (int) res; // ***Return int type.
    }
}

  


Lesson learned:

1.Overflow

2.Difference between Integer's maximum and minimum

3. How to check the overflow

4. A FUNCTION: (condition) ? result1 : result2


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值