[LeetCode] 7. Reverse Integer

题目链接:传送门

Description

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.

Solution

题意:

给定一个 32-bit signed integer,求这个数反转后的值,若反转后的值不在 32-bit signed integer 的表示范围内,输出0

思路:

中间用long long处理,过程中注意判一下 32-bit signed integer 这个的范围即可

class Solution {
public:
    int reverse(int x) {
        long long y = abs(x);
        vector<int> nums;
        while (y) {
            nums.push_back(y % 10);
            y /= 10;
        }
        long long res = 0, base = 1;
        for (int i = nums.size() - 1; i >= 0; i--, base *= 10) {
            res += base * nums[i];
            if (res > (1LL << 31))  break;
        }
        if (x < 0)  res *= -1;
        if (res > ((1LL << 31) - 1) || res < -(1LL << 31))  res = 0;
        return (int)res;
    }
};
posted @ 2018-02-13 00:58  酒晓语令  阅读(124)  评论(0编辑  收藏  举报