leetcode_7. Reverse Integer

題目:

Reverse digits of an integer.

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

click to show spoilers.

Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Subscribe to see which companies asked this question.

簡單題:就是輸入一個數,反轉它的數值。如果超過了int32,就return 0


class Solution {
public:
    int reverse(int x) {
        long long ans=0;
        if(x==0){
            return 0;
        } else if(x<0){
           // ans=ans*(-1);
            int y=-x;
            while(y){
                int k=y%10;
                y=y/10;
                ans=ans*10+k;
            }
            if (ans > INT_MAX || ans < INT_MIN){
                return 0;
            }
            return -ans;
        } else {
            int y=x;
            while(y){
                int k=y%10;
                y=y/10;
                ans=ans*10+k;
            }
            if (ans > INT_MAX || ans < INT_MIN){
                return 0;
            }
            return ans;
        }
    }
};

發佈了27 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章