leetcode 7. 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

先保存一下正负号,然后判断一下是否溢出。

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

这题感觉很水,看答案好像出题人想复杂了hh

posted @ 2020-05-08 19:51  winechord  阅读(55)  评论(0编辑  收藏  举报