題目:
Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.題目大意:
反轉(zhuǎn)數(shù)字的整數(shù)。
Example1: x = 123,return 321
Example2:x = -123,return -321
解題思路
為防止越界,直接使用long long類型來進行存儲,可以簡化計算。
最終輸出前判斷下是否溢出即可。
具體實現(xiàn)
//1:借用了標準中的INT_MIN和INT_MAX來判斷是否越界
class Solution {
public:
int reverse(int x) {
long long lresult = 0;
while(x)
{
lresult = lresult*10 + x%10;
x /= 10;
}
return (lresult < INT_MIN || lresult > INT_MAX)?0:lresult;
}
};
// 使用回溯的方式來判斷是否越界
public int reverse(int x)
{
int result = 0;
while (x != 0)
{
int tail = x % 10;
int newResult = result * 10 + tail;
if ((newResult - tail) / 10 != result)
{ return 0; }
result = newResult;
x = x / 10;
}
return result;
}
你有沒有想過這個?
以下是編碼前要問的一些好問題。如果您已經(jīng)考慮過這一點,很贊!
如果整數(shù)的最后一位是0,輸出應該是多少?即,例如10,100。
你注意到反轉(zhuǎn)的整數(shù)可能會溢出嗎?假設輸入是一個32位整數(shù),則1000000003的倒數(shù)溢出。你應該如何處理這種情況?
為了這個問題的目的,假設當反轉(zhuǎn)的整數(shù)溢出時,你的函數(shù)返回0。