007 Reverse Integer 旋转整数

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;
    }
};

 

posted on 2018-03-31 14:33  lina2014  阅读(104)  评论(0编辑  收藏  举报

导航