码迷,mamicode.com
首页 > 编程语言 > 详细

Reverse Integer leetcode java

时间:2015-12-16 17:11:35      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

问题描述:

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;
    }

 

Reverse Integer leetcode java

标签:

原文地址:http://www.cnblogs.com/mydesky2012/p/5051488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!