[LeetCode

来源:互联网 发布:擎天软件科技有限公司 编辑:程序博客网 时间:2024/05/23 11:55

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 = 0num表示题目给定的数字的绝对值:
    • 判断res是否溢出,判断方法为INT_MAX / 10 < res || (INT_MAX - num % 10) < res * 10,其中INT_MAX表示32位有符号整数的最大值,前一个条件判断 res*10是否溢出, 后一个条件判断 res*10 + num%10 是否溢出:
      • 如果是,则终止循环,返回0
      • 如果否,则继续循环计算
    • res = res * 10 + num % 10
    • num = 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

0 0
原创粉丝点击