LeetCode 7 — Reverse Integer(反轉整數)

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, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

翻譯
給定一個 32 位有符號整數,將整數中的數字進行反轉。

示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能存儲 32 位有符號整數,其數值範圍是 [−231, 231 − 1]。根據這個假設,如果反轉後的整數溢出,則返回 0。

分析
轉化爲字符串再處理,轉化回來時先轉化成long long,範圍合理再轉爲int。

c++實現

class Solution {
public:
    int reverse(int x) {
        stringstream ss;
        ss << x;
        string a = ss.str();
        if (a[0] == '-')
        {
            for (int i = 1; i <= (a.length()-1)/2; i++)
            {
                char tmp;
                tmp = a[i];
                a[i] = a[a.length()-i];
                a[a.length()-i] = tmp;
            }
        }
        else
        {
            for (int i = 0; i <= (a.length()-1)/2; i++)
            {
                char tmp;
                tmp = a[i];
                a[i] = a[a.length()-1-i];
                a[a.length()-1-i] = tmp;
            }
        }
        stringstream tt(a);
        long long t;
        tt >> t;
        if (t > pow(2,31)-1 || t < -1*pow(2,31) )
            return 0;
        int result;
        stringstream yy(a);
        yy >> result;
        return result;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章