首页 > 代码库 > 【LeetCode】7. Reverse Integer

【LeetCode】7. Reverse Integer

题目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

简单题,需要考虑两个问题,1)如果输入的末尾是0怎么办?2)如果倒过来的数字溢出了怎么办?

class Solution {public:    int reverse(int x) {        int flag = 1;        unsigned res = 0;;        if (x < 0){            flag = -1;            x = flag * x;        }                while (x > 0)        {            if (res > (INT_MAX - x%10)/10)                    return 0;            res = res*10 + x%10;            x = x/10;        }                return flag * (int)res;    }};

 

【LeetCode】7. Reverse Integer