題目
給出一個 32 位的有符號整數,你需要將這個整數中每位上的數字進行反轉。
示例 1:
輸入: 123
輸出: 321
示例 2:輸入: -123
輸出: -321
示例 3:
輸入: 120
輸出: 21
注意:
假設我們的環境只能存儲得下 32 位的有符號整數,則其數值範圍爲 [−231, 231 − 1]。請根據這個假設,如果反轉後整數溢出那麼就返回 0。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-integer
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
分析
- 將整數轉換成字符串,然後將字符串倒序,再將字符串轉換爲整數。需要考慮什麼呢?倒序後整數溢出,以及負數應該怎麼處理
- 數學法,只需要知道取餘數和取商的區別,即可簡單實現倒序。
實現
轉字符串
class Solution {
public:
int reverse(int intA) {
long long re = 0;
bool IsMinus = false;
if (intA < 0)
{
IsMinus = true;
}
if (intA > INT_MAX)
{
return 0;
}
bool IsZero = true;
string strA = to_string(intA);
string strRe;
for (int i = strA.size() - 1; i >= 0; i--)
{
int a = strA.at(i);
if (a == 0 && IsZero)
{
continue;
}
IsZero = false;
strRe += strA.at(i);
}
re = atoll(strRe.c_str());
if (re > INT_MAX)
{
return 0;
}
return IsMinus ? -re : re;
}
};
數學法
class Solution {
public:
int reverse(int intA) {
//使用long long類型,防止反轉後溢出。
long long re = 0;
if (intA > INT_MAX)
{
return 0;
}
if (intA == INT_MIN)
{
return 0;
}
bool blnISMinus = false;
if (intA < 0)
{
blnISMinus = true;
intA = -intA;
}
int digit = 0;
while (intA > 0)
{
digit = intA % 10;
intA /= 10;
re = re * 10 + digit;
}
if (re > INT_MAX)
{
return 0;
}
return blnISMinus ? -re : re;
}
};