力扣第7题-- 整数反转

在这里插入图片描述

题目本身不难但是有一个坑(反转的数可能会超过int的最大值)那么这个答案应该返回0;

例如传入1534236469,末尾数是9,在进行ans = ans * 10 + x % 10;很容易造成越界

class Solution {
    
    
    public int reverse(int x) {
    
    
        int ans = 0;
        while (x != 0) {
    
    //说明没有移除完
            if ((ans * 10) / 10 != ans) {
    
     // 处理过程中如果遇到越界则会返回0;
                ans = 0;
                break;
            }
            ans = ans * 10 + x % 10; // 得到反转的整数值
            x = x / 10;//移除一位
        }
        return ans;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_41813208/article/details/109301418