題目地址:https://leetcode-cn.com/problems/reverse-integer/
題目描述
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
題目示例
示例 1:
輸入: 123
輸出: 321
示例 2:
輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:假設我們的環境只能存儲得下 32 位的有符號整數,則其數值范圍為 [−231, 231 − 1]。請根據這個假設,如果反轉后整數溢出那么就返回 0。
解題思路
思路1:逆序累加處理,需要注意的是逆序結果可能出現溢出情況,為避免此種情況,使用long long類型存儲反轉結果,並對大於上限和下限值返回0,同時,因為負數取模結果還是負數,所以無需額外處理,時間復雜度O(logn)。
思路2:整數轉換字符串處理,利用to_strin()函數將整數x轉換為字符串s,然后使用反轉函數reverse()將除過符號位的數字進行反轉,最后進行溢出判斷即可。
程序源碼
思路1
class Solution { public: int reverse(int x) { long res = 0; while(x) { res = res *10 + x % 10; x /= 10; } if(res < INT_MIN || res > INT_MAX) return 0; return res; } };
思路2
class Solution { public: int reverse(int x) { long res; string s = to_string(x); int pos = s.find_first_not_of('-'); //在字符串s中尋找第一個不以'-'字符開始的位置 std::reverse(s.begin() + pos, s.end()); //對字符串是種除符號位的其它字符進行反轉操作, istringstream cout(s); cout >> res; //將string類型反轉結果轉換為long類型並輸出到res中 if(res > INT_MAX || res < INT_MIN) return 0; //溢出判斷 return res; } };