LeetCode | 整数反转
LeetCode 整数 反转
2023-06-13 09:15:37 时间
题目 7. 整数反转 - 力扣(LeetCode) 给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。 如果反转后整数超过 32 位的有符号整数的范围 \([−2^{31}, 2^{31} − 1]\) ,就返回 0。 假设环境不允许存储 64 位整数(有符号或无符号)。 示例 1:
输入:x = -123输出:-321
示例 2:
输入:x = -123输出:-321
示例 3:
输入:x = 120输出:21
示例 4:
输入:x = 0输出:0
提示: \(-2^{31} <= x <= 2^{31} - 1\) 题解 C#
public class Solution { public int Reverse(int num) { int rev = 0; while (num != 0) { // 取个位弹出 int pop = num % 10; // 降位: 百位变十位 num = num / 10; // 防止溢出 if (rev > int.MaxValue / 10 || (rev == int.MaxValue / 10 && pop > 7)) return 0; if (rev < int.MinValue / 10 || (rev == int.MinValue / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; }}
相关文章
- LeetCode周赛291,最后5分钟连A两题,不放弃才皆有可能
- LeetCode周赛290,什么?你不会树状数组,这太不公平了
- leetcode-91解码方法(动态规划|记忆化搜索)[通俗易懂]
- Leetcode 题目870-优势洗牌(田忌赛马)
- Leetcode题目054-螺旋矩阵
- LeetCode 905. 按奇偶排序数组
- leetcode 1351. 统计有序矩阵中的负数 js实现
- LeetCode题解——哈希表篇
- 【动态规划】LeetCode 题解:494-目标和
- 刷完这19道leetcode二分查找算法,不信进不了大厂
- LeetCode-347-前K个高频元素
- 每日一道leetcode:8. 字符串转换整数 (atoi)