[LeetCode - 数学] 7. Reverse Integer

xiaoxiao2021-02-27  330

1 题目

Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321

2 分析

本题的解决主要依靠存在的数学关系:令 num 表示任意数字,那么

num % 10 表示 num 的最后一位数字num / 10 表示 num 去掉最后一位数字的值

根据上面的规律,可以把给定的数字逐位的进行上述运算, 求出 reverse number, 伪代码如下:

初始化res = 0,表示要求的数值初始化sign = 1, 表示给定的数字的正负,如果为负,sign = -1执行以下循环,循环的终止条件是 num = 0,num表示题目给定的数字的绝对值: 判断res是否溢出,判断方法为INT_MAX / 10 < res || (INT_MAX - num % 10) < res * 10,其中INT_MAX表示32位有符号整数的最大值,前一个条件判断 res*10是否溢出, 后一个条件判断 res*10 + num 是否溢出: 如果是,则终止循环,返回0如果否,则继续循环计算res = res * 10 + num % 10num = num / 10

将sign * num作为返回值返回 算法的时间复杂度为 O(n) , n 为给定的数字的位数。

3 代码[1]

class Solution { public: int reverse(int x) { int sign = x < 0 ? -1 : 1; x = abs(x); int res = 0; while (x > 0) { if (INT_MAX / 10 < res || (INT_MAX - x % 10) < res * 10) { return 0; } res = res * 10 + x % 10; x /= 10; } return sign * res; } };

[1]代码来源:https://discuss.leetcode.com/topic/6104/my-accepted-15-lines-of-code-for-java/3

转载请注明原文地址: https://www.6miu.com/read-1515.html

最新回复(0)