LeetCoded第七题:Reverse Integer(C++)详解
Reverse Integer
题目描述:
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:
long reverse(int x) {
long result = 0;//防止越界,所以定义为long
while (x != 0) {
result = 10 * result + x % 10;//求每一位的值
x /= 10;//从首位以此到个数位
}
return (result > INT_MAX || result < INT_MIN) ? 0 : result;//这里有个判断是否越界的问题
}
};
性能:
解题思想:从首位至个数位依次循环,以此将数值放置到result中,得到数值。最后考虑越界问题。