LeetCode-Reverse Integer

Description:
Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output: 321

Example 2:

Input: -123
Output: -321
重点内容
Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

第一种解法:用一个数组将给定数字的各个位保存下来,并且记录此时的符号,用长整型保存反转后的数字,防止溢出,与整型的最大最小值比较可判断是否溢出;

class Solution {
    public int reverse(int x) {
        int op = 1;//数字的符号
        if(x < 0){
            op = -1;
            x *= op;
        }
        int len = 0;
        int nums[] = new int[32];//保存各位数字
        while(x != 0){
            nums[len++] = x%10;
            x /= 10;
        }
        long result = 0L;//用长整型保存数字,防止溢出
        int order = len-1;//数字的阶
        for(int i=0; i<len; i++){
            result += (nums[i]*Math.pow(10, order--));
        }
        if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){//判断是否溢出
            return 0;
        }
        return (int)result*op;
    }
}

第二种解法:对于result = result*10 + num可能造成的溢出情况有以下几种

  1. 对于正数来说:(2147483647)
    如果result > Integer.MAX_VALUE/10,此时溢出
    如果result == Integer.MAX_VALUE/10 && num>7,此时溢出
  2. 对于负数来说:(-2147483648)
    如果result < Integer.MIN_VALUE/10,此时溢出
    如果result == Integer.MIN_VALUE/10 && num<-8,此时溢出
class Solution {
    public int reverse(int x) {
        int op = 1;//数字的符号
        if(x < 0){
            op = -1;
            x *= op;
        }
        int len = 0;
        int nums[] = new int[32];//保存各位数字
        while(x != 0){
            nums[len++] = x%10;
            x /= 10;
        }
        long result = 0L;//用长整型保存数字,防止溢出
        int order = len-1;
        for(int i=0; i<len; i++){
            result += (nums[i]*Math.pow(10, order--));
        }
        if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE){//判断是否溢出
            return 0;
        }
        return (int)result*op;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80886860