任务三(letecode)

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

class Solution {
public:
int reverse(int x) {
int flag = 1;
if(x < 0){
flag = -1;
x = -x;
}
long long sum = 0; //用long来得到结果
while(x){
sum = (sum * 10 + (x % 10));
x /= 10;
}
sum = sum * flag;
return (sum > INT_MAX || sum < INT_MIN)? 0 : sum;
}
};

猜你喜欢

转载自blog.csdn.net/weixin_41741008/article/details/88975703