Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

LeetCode: Reverse Integer 解题报告

SOLUTION 1:

注意越界后返回0.先用long来计算,然后,把越界的处理掉。

public class Solution {
    public int reverse(int x) {
        long ret = 0;
        
        while (x != 0) {
            ret = ret * 10 + x % 10;
            x /= 10;
        }
        
        if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) {
            return 0;
        }
        
        return (int)ret;
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-09-18
  • 2021-10-16
  • 2022-01-14
  • 2021-11-02
  • 2021-11-01
  • 2022-01-06
  • 2021-11-18
猜你喜欢
  • 2022-12-23
  • 2022-01-24
  • 2021-09-14
  • 2022-12-23
  • 2021-09-07
  • 2021-10-03
  • 2021-07-26
相关资源
相似解决方案