題目描述:
對(duì)于輸入的一個(gè)整數(shù),對(duì)它進(jìn)行翻轉(zhuǎn)操作。但是反轉(zhuǎn)后的數(shù)字不能超過32-bit signed integer range: [?231, 231 ? 1].
解題思路:
(有的解題思路復(fù)雜,但是多思考思考沒有壞處~~)
- 用long long型來存儲(chǔ)翻轉(zhuǎn)后的數(shù)字,如果數(shù)字超過INT_MAX,則輸出0,否則輸出翻轉(zhuǎn)后的數(shù)字。
class Solution {
public:
int reverse(int x) {
long long reverse = 0;
bool ispositive = true;
if (x < 0) {
ispositive = false; // 判斷輸入數(shù)字的正負(fù)
x *= -1; // 變?yōu)檎龜?shù)
}
while (x > 0){ //翻轉(zhuǎn)數(shù)字
reverse = reverse * 10 + x % 10;
x /= 10;
}
if (reverse > INT_MAX) return 0;
if (ispositive)
return reverse;
else
return -reverse;
}
};
2.用字符數(shù)組存儲(chǔ)讀入的數(shù)字,判斷長度和每一位的數(shù)字是否超過INT_MAX的每一位數(shù)字。