zoukankan      html  css  js  c++  java
  • Reverse Integer leetcode java

    问题描述:

    Reverse digits of an integer.

    Example1: x = 123, return 321
    Example2: x = -123, return -321

    分析:将一个整数逆序输出,需要判断是否越界。Integer.MAX_VALUE,Integer.MIN_VALUE,由于要进行正、负越界判断,因此,若是负数,则要转换为整数

    代码

    public int reverse(int x) {
            
             int ret = 0;
            int digit = 0;
            boolean neg_flag = false;
        
            if (x < 0) {
                neg_flag = true;
                x = -1 * x;  //covert to abs(x), and record the symbol of negative or positive. 
            }
                
            while (x != 0) {
                digit = x % 10; //get the last digit of x,获得x的最末尾数字
                
                //if ret overflows?
                if (ret != 0) {  //must follow this pattern to check 
                    if ((Integer.MAX_VALUE - digit) / ret < 10 ) 
                        return 0;
                        
                    if (neg_flag == true) {
                        if (-10 < (Integer.MIN_VALUE + digit) / ret) 
                        // - (ret * 10 + digit) < Integer.MIN_VALUE
                        //if we convert the number to abs, we need to compare it in negative form with Integer.MIN_VALUE
                       return 0;
                    } 
                }
                
                ret = ret * 10 + digit;
                x = x / 10; //chop off the last digit of x,斩断x的最末尾数字
            }
            
            if (neg_flag == true)
                ret = -1 * ret;
                
            return ret;
        }
  • 相关阅读:
    Timer Pattern
    la négation
    expression de la fréquence
    .NET 索引器
    JQuery.Gantt(甘特图) 开发指南
    .NET 预处理器指令
    .NET 数据类型之匿名类型(var)
    .NET base与this
    .NET using关键字
    .NET 基础语句
  • 原文地址:https://www.cnblogs.com/mydesky2012/p/5051488.html
Copyright © 2011-2022 走看看