LeetCode-Reverse Integer的一种算法
题目链接:https://leetcode.com/problems/reverse-integer/description/
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
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.
由题意可知,本次题目要求我们将一个整数翻转过来,保留其正负。
需要注意的是,这个题目存在溢出的现象,所以需要判断翻转之后的数是否溢出。由于其溢出的判别是整形,所以计算时使用long来保存翻转后的数。
具体算法是将一个数翻转的算法流程是先取余得到个位数,然后放入新量中,同时原数除以十,删去被存放的个位数,而新量在得到新的个位数方式是先乘以十再相加。在得到结果后判断结果是否溢出。
具体算法如下:
class Solution {
public:
int reverse(int x) {
long ret = 0;
while (x != 0) {
ret = ret*10+x%10; //乘十再加个位数
x = x/10; //除十删去个位数
}
if (ret < -2147483648 || ret > 2147483647) { //判断溢出
return 0;
}
return ret;
}
};
本次算法唯一难点在于判断溢出与否,结果采用long形式保存也是为了更好的判断溢出。