看到題目,會覺得很簡單,相信大家肯定都遇到過這種題,但是本題唯一的難點在於溢出的判斷。
我想了兩種辦法,一種是常規的取模反轉,另一種是字符串法。
方法一(取模反轉法):
如果使用這個方法,我們要知道題目所給的數值範圍:2^31-1=2147483647,-2^31=-2147483648
。
接下來我們只要找到溢出條件:取模到極限值的最後一位時的判斷,詳見下方代碼註釋。
#include <iostream>
using namespace std;
/**
* LeetCode
* 7. 整數反轉 - 取模反轉法
* https://space.bilibili.com/54183978
*/
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x != 0){
int tem = x % 10;
// ans大於214748364 或者 ans=214748364且最後一位大於7
if( ans > INT_MAX / 10 || (ans == INT_MAX / 10 && tem > 7)) return 0;
// ans小於214748364 或者 ans=214748364且最後一位小於-8
if( ans < INT_MIN / 10 || (ans == INT_MIN / 10 && tem < -8)) return 0;
ans = ans*10 + tem;
x = x / 10;
}
return ans;
}
};
int main(){
Solution solution;
cout << solution.reverse(-123);
}
測評結果:
1032 / 1032 個通過測試用例
狀態:通過
執行用時: 4 ms
內存消耗: 5.8 MB
方法二(字符串法):
這個方法會比較低效,其核心思想是對整數取模,每位取出來的數字轉成字符,拼接到新的字符串上實現反轉。然後利用C++的異常捕捉機制來判斷是否運算溢出。
這裡要知道C++中的int和string互轉的方法:
int轉string:to_string
string轉int:stoi
/**
* LeetCode
* 7. 整數反轉 - 字符串方法(效率很低)
* https://space.bilibili.com/54183978
*/
class Solution {
public:
int reverse(int x) {
string ans = "";
int flag = 0;
if(x < 0){
flag = 1;
ans = "-";
}
while(x!=0){
if(flag){
// to_string:int轉string
ans = ans + to_string(-(x%10));
} else{
ans = ans + to_string(x%10);
}
x /= 10;
}
try{
// string轉int
return stoi(ans);
} catch (std::invalid_argument) {
return 0;
} catch (std::out_of_range&) {
return 0;
}
}
};
int main(){
Solution solution;
cout << solution.reverse(-123);
}
測評結果:
(其實結果不是很準,第一次跑貌似用時和消耗都只擊敗了百分之幾的用戶,僅供參考!)