#7_整数反转

Category Difficulty Likes Dislikes
algorithms Easy (33.90%) 1768 -

我的答案

public int reverse(int x) {
    int res = 0;
    int tmp = 0;
    int tmp_res;
    while(x != 0){
        tmp = x % 10;
        tmp_res = res;
        res = res * 10 + tmp;
        if((res - tmp) / 10 != tmp_res){
            return 0;
        }
        x = x / 10;
    }
    return res;
}

解题思路

  • 先不考虑溢出,这是很容易实现的
  • 怎么判断溢出,如果溢出了,那肯定就不正确了,回不去原来的数了
  • 我们先把原来的值存起来
  • 在每次加上去之后反向操作判断跟原来的是不是一样

答案分析

时间复杂度 O(n)

空间复杂度 O(1)

参考方案

  • 溢出,要么是大于最大值,要么是小于最小值
  • 不能在溢出之后再判断,要在溢出前一个判断
  • 当 res > Max_value / 10 再加上去就不行了,等于的话最多还能加 7
  • 当 res < Min_value / 10 再减下去就不行了,等于的话最多还能减 8
public int reverse(int x) {
    int res = 0;
    int tmp = 0;
    while(x != 0) {
        tmp = x % 10;
        if(res > Integer.MAX_VALUE / 10 
        || (res == Integer.MAX_VALUE / 10 && tmp > 7)){
            return 0;
        }
        if(res < Integer.MIN_VALUE / 10
        || (res == Integer.MIN_VALUE / 10 && tmp < -8)){
            return 0;
        }
        res = res *10 + tmp;
        x = x / 10;
    }
    return res;
}

时间复杂度 O(logn)

空间复杂度 O(1)

备注

  • 曾经想对正负情况进行判断,但发现是一样的

  • Integer 的 API

static int              MAX_VALUE
static int              MIN_VALUE
static int              SIZE
static Class<Integer>   TYPE



原文地址:https://www.cnblogs.com/mdz3201/p/leetcode_7.html