题目
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: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows
题意
输入一个32位整数,要求逆序输出。
分析
样例1、2正常逆序输出;
样例3输入数字末尾带0,逆序输出时应当舍去0。
*if(!x) 表示条件为0执行语句,while(x)表示持续执行直到x=0。
*先将int型转换成longlong型,最后判断是否溢出。
代码
class Solution {
public:
int reverse(int x) {
if(!x) return 0;
while(x % 10 == 0) x /= 10;
long long sum = 0;
while(x) {
sum = sum * 10 + x % 10;
x /= 10;
}
int numb = sum;
if(numb == sum) return numb;
else return 0;
}
};
待解
class Solution {public:}含义?