zoukankan      html  css  js  c++  java
  • # leetcode #[7. 整数反转]

    leetcode

    7. 整数反转

    class Solution {
        public int reverse(int x) {
    
            boolean isNegative = false;
            if(x < 0){
                isNegative = true;
            }
    
            int ans = 0;
            while(x != 0){
                
                // 负数的取模仍然为负数
                int pop = x % 10;
    
                // 为了防止“ans * 10 + pop”的值可能溢出
                // 需要用Integer.MAX_VALUE 或 Integer.MIN_VALUE进行提前计算并判断
    
                // 如果是正数,先提前判断是否溢出,因为pop大于等于0
                // 所以Integer.MAX_VALUE - pop的值仍然不会溢出
                if(!isNegative && ans > (Integer.MAX_VALUE - pop) / 10){
                    return 0;
                }
                // 如果是负数,先提前判断是否溢出,因为pop小于0
                // 所以Integer.MIN_VALUE - pop的值大于MIN_VALUE,仍然不会溢出
                else if(isNegative && ans < (Integer.MIN_VALUE - pop) / 10){
                    return 0;
                }
                // 正常情况下的翻转逻辑
                else{
                    ans = ans * 10 + pop;
                }
                x = x / 10;
            }
    
            return ans;
        }
    }
    
  • 相关阅读:
    javascript对象继承的实现
    浏览器兼容问题汇总<转>
    DOM笔记
    Ajax日记
    学习态度
    项目1
    导航项目-整体布局
    有关布局
    导航项目开始
    windows 服务 定时程序 跑不出数据
  • 原文地址:https://www.cnblogs.com/cnblogszs/p/13418271.html
Copyright © 2011-2022 走看看