LeetCode第7號(hào)問(wèn)題:整數(shù)反轉(zhuǎn)
題目描述
給出一個(gè) 32 位的有符號(hào)整數(shù),你需要將這個(gè)整數(shù)中每位上的數(shù)字進(jìn)行反轉(zhuǎn)。
示例:
輸入: 123
輸出: 321
輸入: -123
輸出: -321
輸入: 120
輸出: 21
注意:
假設(shè)我們的環(huán)境只能存儲(chǔ)得下 32 位的有符號(hào)整數(shù),則其數(shù)值范圍為 [?231, 231 ? 1]。請(qǐng)根據(jù)這個(gè)假設(shè),如果反轉(zhuǎn)后整數(shù)溢出那么就返回 0。
解法(java)
每次彈出數(shù)字'x'最后一位,并壓入到'res'的后面,全部壓入后,'x'與'res'即完全相反;
在不使用數(shù)據(jù)結(jié)構(gòu)的情況下可以借助數(shù)學(xué)方法來(lái)實(shí)現(xiàn)“彈出/壓入”的操作:
// 彈出
pop = x % 10
x /= 10
// 壓入
temp = y * 10 + pop
y = temp
此方式有溢出風(fēng)險(xiǎn),使用時(shí)應(yīng)注意每次反轉(zhuǎn)后是否溢出。
反轉(zhuǎn)后數(shù)字的溢出情況可以使用Integer.MAX_VALUE和Integer.MIN_VALUE來(lái)實(shí)現(xiàn)
參考代碼:
class Solution {
public int reverse(int x) {
long res = 0;
while(x != 0) {
res = res * 10 + x % 10;
x /= 10;
}
return res > Integer.MAX_VALUE || res < Integer.MIN_VALUE ? 0 : (int)res;
}
}