題目描述
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)制表示的長(zhǎng)度)廉丽。
如果不使用 long long 型變量,可以通過(guò)檢測(cè)每次 y = y * 10 + x % 10
操作后貌踏,比較y
除 10 的余數(shù)與上一次的y
值十气,如果不同,發(fā)生溢出瑟枫。經(jīng)過(guò)測(cè)試斗搞,與上述方法在運(yùn)行時(shí)間上沒(méi)有明顯差別。