整数反转(Python and C++解法)

题目:

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321
 示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21
注意:

假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231,  231 − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer

思路:

可以直接辗转相除,依次获得原始数据尾巴的数字;也可以采用双指针法,跳过特殊条件。

需要考虑三处细节:1.负号;2.数字尾巴的‘0’;3.数字溢出;

Python解法:

 1 class Solution:
 2     def reverse(self, x: int) -> int:
 3         if x == 0:  # 这种情况需要特殊考虑,负责tail会数组越界
 4             return 0
 5         numStr = list(str(x))  # python的字符串不能直接操作下标,需要转换为列表
 6         lenStr = len(numStr)
 7         head = 0
 8         tail = lenStr - 1
 9         storeIndex = 0  # 记录数据除‘0’之外的末尾数字的位置
10         while numStr[head] == '-':
11             head += 1
12         while numStr[tail] == '0':
13             tail -= 1
14         storeIndex = tail
15         while head < tail:
16             numStr[head], numStr[tail] = numStr[tail], numStr[head]
17             head += 1
18             tail -= 1
19         strNum = int(''.join(numStr[:storeIndex + 1]))  # 列表需要先转换为字符串,再转换为数字
20         if strNum >= -2147483648 and strNum <= 2147483647:
21             return strNum
22         return 0

C++解法:

 1 class Solution {
 2 public:
 3     int reverse(int x) {
 4         if(x == -2147483648 || x == 2147483647)  // 当输入数字整好是边界值时,不能正确进行正负转换,需要提前判断
 5             return 0;
 6         bool flag = false;
 7         if(x < 0) {  // 转换为正数统一处理
 8             x = -x;
 9             flag = true;
10         }
11         long long num = 0;  // 不能申请为int型
12         while(x) {
13             num = num * 10 + x % 10;
14             x = x / 10;
15         }
16         if(flag)
17             num = -1 * num;
18         if(num >= -2147483648 && num <= 2147483647)
19             return num;
20         return 0; 
21     }
22 };
原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/13516848.html