leetcode第七題:Reverse Integer
阿新 • • 發佈:2019-01-10
題目:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [-2147483648,2147483647]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解題思路:
該題目思路簡單,要注意的是int型別的整數範圍是[-2147483648,2147483647],因此當-2147483648和2147483647取反後將不再是int型別,因此解決該題目的思路是可以先將傳進來的數值賦值給long long型變數,然後對long long型變數進行取反,如果取反後的數值大於INT_MAX,則應返回0。C++程式碼如下:
class Solution {
public:
int reverse(int x)
{
long long y = x;
bool flag = true;
if (y<0)
{
flag = false;
y = -y;
}
long long res = 0;
while(y>0)
{
res = res * 10+y % 10;
y = y / 10;
}
if(res>INT_MAX)
{
return 0;
}
if(flag)
{
return res;
}
else
{
return -res;
}
}
};
執行結果: