7. Reverse Integer

2023-05-16

文章目录

      • Reverse Integer
      • solution
      • Algorithm

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

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

7. Reverse Integer 的相关文章

随机推荐