Leetcode第七题:Reverse Integer

题目地址:Reverse Integer


题目简介:给出一个数字得到从后往前输出的结果,如果大于所需要的结果,那么将输出0;

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.

题目解答:

C++版:

class Solution {
public:
    int reverse(int x) {
        double ans = 0;
        double positive = 2147483647;
        double negative = -2147483648;
        if (x < 0)
        {
            if (x == negative)
                return 0;
            int temp = -1 * x;
            while (temp >= 10)
            {
                ans += (temp % 10);
                temp /= 10;
                ans *= 10;
            }
            ans += temp;
            ans *= -1;
            if (ans < negative)
                return 0;
            else
                return (int)ans;
        }
        else
        {
            while (x >= 10)
            {
                ans += (x % 10);
                x /= 10;
                ans *= 10;
            }
            ans += x;
            if (ans > positive)
                return 0;
            else
                return (int)ans;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/chao_shine/article/details/88084656