欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7. Reverse Integer

程序员文章站 2022-07-15 14:39:23
...

Reverse Integer

Easy

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.

solution

class Solution {
    public int reverse(int x) {
        if(x == 0 || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)//刚开始也要判断
            return 0;
        int ret = 0;
        int y = Math.abs(x);
         while(y > 0){
              int d = y % 10;
              if(ret > Integer.MAX_VALUE/10 || (ret== Integer.MAX_VALUE/10 && d > 7) ) 
                  return 0;//在中间的push过程中可能会overflow  Integer的最大值2147483647

              if (ret < Integer.MIN_VALUE/10 || (ret == Integer.MIN_VALUE / 10 && d < -8)) 
                  return 0;//Integer的最小值-2147483648
              ret = ret * 10 + d;
              y = y / 10;
            }
        if(x < 0)
            ret = -ret;
        return ret;
    }
}

32bit也就是4个字节,也就是int类型的取值范围

Algorithm

7. Reverse Integer

相关标签: Leetcode