leetcode 7. 反轉整數(c++)

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,  2311]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
class Solution {
public:
    #define INT_MAX 2147483647
    #define INT_MIN (-INT_MAX-1)
    int reverse(int x) {
        int flag=x<0?-1:1;
        int num=0;
        while(x){
            if((flag==-1&&(INT_MIN/10>num))||(flag==1&&INT_MAX/10<num))return 0;
            num=num*10+x%10;
            x/=10;
        }
        return num;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章