LeetCode 之 Reverse Integer — C++ 實現

Reverse Integer

 

Reverse digits of an integer.

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

將一個整數按數字翻轉。

分析:

    每次取數字的最低位作爲翻轉後整數的最高位,計算時就要進行溢出判斷,爲防止溢出用 long long int 作爲翻轉後計算的結果。

注意:正數和負數的邊界是不一樣的。

class Solution {
public:
    int reverse(int x) {
        const int max = 0x7fffffff;  //int最大值  
        const int min = 0x80000000;  //int最小值  
        long long int rev = 0;
 
        while(x)
        {
            rev = 10*rev + x % 10;
            if((rev > max) || (rev < min)) //越界
            {
                return 0;
            }
            x = x / 10;
        }
        
        return rev;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章