7. Reverse Integer——LeetCode OJ
阿新 • • 發佈:2019-02-07
Difficulty:Easy
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Example 2:
Input: -123
Output: -321
Example 3:
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
給定一個32位有符號整型數,將它反轉輸出。注意可以儲存的32位有符號整型數範圍是[-2^31,2^31-1]。
注意反轉後的數可能超出範圍。所以該數需要用比int範圍大的型別來儲存。
class Solution {
public:
int reverse(int x) {
long res = 0;
while(x!=0)
{
res = res * 10 + x % 10;
x /= 10;
}
if (res > INT_MAX || res < INT_MIN)
{
return 0;
}
return res;
}
};
Runtime: 30 ms