算法题补卡-2020-11-3-数字反转+溢出

力扣-7.整数反转

考点:简单/循环/边界

这个题没什么技术含量,唯一要注意的两个点:

  1. 符号
  2. 值溢出问题

代码:

class Solution {
    
    
    public int reverse(int x) {
    
    
    	// 用于记录符号的 f
        int f = x > 0 ? 1 : -1;
        int ans = 0;
        // 将 x 统一为正整数
        x = Math.abs(x);
        // 开始转化
        while(x > 0) {
    
    
        	// 一旦 ans 大于 最大值的十分之一,那说明这次累加一定会溢出
        	// 或者 正好等于最大值的整除 10 的值,但是本次要加上的值大于 7 也是一样的道理
            if (ans > Integer.MAX_VALUE / 10 || ans == Integer.MAX_VALUE / 10 && x % 10 > 7) return 0;
            
            // 转化过程 不细说了
            ans= ans * 10 + x % 10;
            x = x / 10;
        }
        // 将符号还给答案
        ans *= f;
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45543674/article/details/109493695