Leetcode#7 Reverse Integer

less than 1 minute read

Published:

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

Idea:

Use “unsigned long long” to check integer overflow

Solution:

class Solution {
    public:
        int reverse(int x) {
            int y = x >= 0 ? 1 : -1;

            unsigned long long tmp = 0;
            if(x < 0) {
                x = x*(-1);
            }

            while(x>0) {
                tmp = tmp*10 + x%10;
                if (tmp > INT_MAX)
                    return 0;
                x = x/10;
            }

            if (y == -1)
                tmp = tmp * (-1);

            return tmp;
        }
};