題目描述
Reverse digits of an integer.
Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
輸入與輸出
class Solution {
public:
int reverse(int x) {
}
};
樣例
Example1: x = 123, return 321.
Example2: x = -123, return -321.
題解與分析
新建一個(gè)整型變量,翻轉(zhuǎn)即可。為了防止溢出,可以使用 long long 型變量。
C++ 代碼如下:
class Solution {
public:
int reverse(int x) {
if (x == 0)
return 0;
long long y = 0;
while (x != 0)
y = y * 10 + x % 10, x = x / 10;
if (y > INT_MAX || y < INT_MIN)
return 0;
return y;
}
};
該算法的時(shí)間復(fù)雜度為 O(logn)(10進(jìn)制表示的長度)。
如果不使用 long long 型變量,可以通過檢測每次 y = y * 10 + x % 10 操作后,比較y除 10 的余數(shù)與上一次的y值,如果不同,發(fā)生溢出。經(jīng)過測試,與上述方法在運(yùn)行時(shí)間上沒有明顯差別。