difficult:easy #728
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: [−$2^{31}$ , $2^{31}$ − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法
int reverse(int x) {
int result = 0;
while (x != 0 ) {
int num = x % 10;
if (result > INT_MAX / 10 || (result == INT_MAX / 10 && num > 7)) return 0;
if (result < INT_MIN / 10 || (result == INT_MIN / 10 && num < -8)) return 0;
x = x / 10;
result = result * 10 + num;
}
return result;
}
版权声明:原创,转载请注明来源,否则律师函警告
本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!