LeetCode Reverse Integer 帶考慮第二種特殊情況
Reverse Integer
Reverse digits of an integer.
Example1:x = 123, return 321
Example2:x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
很簡單的題目,但是如果要考慮到特殊情況的話,還是比較不容易的,下面是accepted的最簡單的程式。
int reverse(int x) {
int result = 0;
while (x)
{
result = result*10 + x%10;
x /= 10;
}
return result;
}
2013. 12.9 update:之前想複雜了,不應該那樣處理,更新一下,使用long long就好了,如下程式:
考慮:
1 溢位
2 + -
3 1000, 10等尾部為零的情況
答案:
1 long long 處理了
2 無需要處理
3 無需要處理
int reverse(int x)
{
long long res = 0;
while (x)
{
res = res*10 + x%10;
x /= 10;
}
if (res >= INT_MAX) return INT_MAX;
if (res <= INT_MIN) return INT_MIN;
return res;
}
最近覺得水平提高了,考慮問題更全面了,寫的程式碼也比以前優雅了。看看下面的程式,還真是很醜。留下來警示一下自己吧。繼續努力吧。
考慮到第二個特殊情況,下面程式也是accepted的,不過好像LeetCode並不測試這個特殊情況。
所以我這裡也只是小小處理了一下:reverse之後如果上溢,返回最大值INT_MAX; 如果是下溢,返回最小值INT_MIN
int reverse(int x) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(-10<x && x<10 || x == INT_MAX || x == INT_MIN) return x;
int xSave = x;
vector<int> vi;
vector<int> viMax;
vector<int> viMin;
bool signX = false;
if(x<0) signX = true;
int maxX = INT_MAX;
int minX = INT_MIN;
while (x!=0)
{
vi.push_back(x % 10);
x /= 10;
if(!signX)
{
viMax.push_back(maxX % 10);
maxX /= 10;
}
else
{
viMin.push_back(minX % 10);
minX /= 10;
}
}
bool upOverInt = false;
bool downOverInt = false;
if(!signX && maxX == 0)
{
for(auto iter1 = vi.begin(); iter1 != vi.end(); iter1++)
{
upOverInt = false;
auto iter2 = viMax.end();
iter2--;
if(*iter1 > *iter2)
{
upOverInt = true;
break;
}
if(*iter1 == *iter2)
{
upOverInt = true;
}
if(!upOverInt) break;
}
}
else if(signX && minX == 0)
{
for(auto iter1 = vi.begin(); iter1 != vi.end(); iter1++)
{
downOverInt = false;
auto iter2 = viMin.end();
iter2--;
if(*iter1 > *iter2)
{
downOverInt = true;
break;
}
if(*iter1 == *iter2)
{
downOverInt = true;
}
if(!downOverInt) break;
}
}
if(upOverInt) return INT_MAX;
if(downOverInt) return INT_MIN;
int i = 0;
int xtemp = 0;
for(auto iter = vi.begin(); iter != vi.end(); iter++)
{
xtemp = xtemp*10 + *iter;
}
return xtemp;
}