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