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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

详见:https://leetcode.com/problems/reverse-integer/description/

实现语言:Java

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

 实现语言:C++

class Solution {
public:
    int reverse(int x) {
        long res=0;
        while(x)
        {
            res=res*10+x%10;
            x/=10;
        }
        return (INT_MAX<res||INT_MIN>res)?0:res;
    }
};

 

相关文章:

  • 2021-06-06
  • 2021-08-08
  • 2021-06-07
  • 2022-12-23
  • 2021-08-01
  • 2021-11-25
  • 2021-04-15
  • 2021-09-30
猜你喜欢
  • 2022-02-17
  • 2022-02-14
  • 2022-12-23
  • 2021-11-06
  • 2021-09-11
  • 2021-08-13
  • 2021-10-10
相关资源
相似解决方案