Problem 7

Reverse Integer

Posted by Ruizhi Ma on July 11, 2019

问题描述

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.

解决思路

对原数循环取余,通过循环乘法和加法,实现reverse原数。需要注意的是,题目给了范文,必须要对数据溢出,已经单独处理。

问题解惑

本来还在想正负号怎么处理,取余的同时不就已经带了正负了吗,真是笨死了!!!
至于为什么一开始res定义成long,是因为题目要求了在int类型范围之内,所以反转的过程可能会造成溢出,所以需要用long类型的res先保存,最后在强制类型转换回int。

代码

class Solution {
    public int reverse(int x) {
        long res = 0;
        
        while(x != 0){
            res = res * 10 + x % 10;
            x /= 10;
        }
        
        if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
        
        return (int)res;
    }
}

小感想

这道题虽然是简单题,但Acceptance还挺低的,我一开始死脑筋,居然想着循环收尾互换位置…还是题做的少,方法见的少,脑子不够活。