Reverse digits of an integer.
反轉(zhuǎn)整數(shù)數(shù)字蝗罗。
Example1: x = 123, return 321
Example2: x = -123, return -321
需要注意的問題:整數(shù)的最低位是0艇棕,如10100.以及反轉(zhuǎn)的數(shù)字可能溢出。
解:
反轉(zhuǎn)一個(gè)數(shù)字就是循環(huán)的除以10串塑,得到的余數(shù)是最低位沼琉,是我們返回的結(jié)果的最高位。這種解法對(duì)于10100這種情況依舊使用桩匪,為了防止溢出則需要一個(gè)判斷語句打瘪。代碼如下(C++):
class Solution { public: int reverse(int x) { int result = 0; while (x != 0){ if (INT_MAX / 10 < result||INT_MIN/10>result){ result = 0; break; } else{ result = result * 10 + x % 10; } x /= 10; } return result; } };
顯然時(shí)間復(fù)雜度為O(n),空間復(fù)雜度為O(1).