題目
Reverse digits of an integer.
Example1: x = 123, return 321Example2: 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.
思路
基本的模運(yùn)算與整除運(yùn)算。判斷溢出這個(gè)倒是有點(diǎn)新奇蔫慧,不過(guò)也不難滓走。
實(shí)現(xiàn)
class Solution {
public:
int reverse(int x) {
long long ans=0, base1=1, base2=1;
while(x/(base1*10)!=0){
base1*=10;
}
while(x/base2!=0){
ans += ((x/base1)%10) * base2;
base1/=10;
base2*=10;
}
if(ans>INT_MAX || ans<INT_MIN) return 0;
return ans;
}
};
思考
走了很多歪路,不過(guò)也有了一些體會(huì):
一是用兩個(gè)基來(lái)取得輸入和輸出的某一位比用其指數(shù)要快一些嗓化;
二是判斷溢出可以用符號(hào)來(lái)判斷也可以用long long配合范圍來(lái)判斷棠涮,這兩者孰優(yōu)孰劣還真不好說(shuō)。
三是從簡(jiǎn)單程度上來(lái)看刺覆,用long long 進(jìn)行運(yùn)算严肪,再判斷范圍會(huì)比較清晰。
四是可以改進(jìn),不需要兩個(gè)基就可以得出答案驳糯,比如:
class Solution {
public:
int reverse(int x) {
long long res = 0;
while(x) {
res = res*10 + x%10;
x /= 10;
}
return (res< INT_MIN|| res>INT_MAX) ? 0 : res;
}
};