[LeetCode
来源:互联网 发布:擎天软件科技有限公司 编辑:程序博客网 时间:2024/05/23 11:55
1 题目
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
2 分析
本题的解决主要依靠存在的数学关系:令
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%10
是否溢出:- 如果是,则终止循环,返回0
- 如果否,则继续循环计算
res = res * 10 + num % 10
num = num / 10
- 判断res是否溢出,判断方法为
将sign * num
作为返回值返回
算法的时间复杂度为
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
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- 本机不安装Oracle客户端,使用PL/SQL Developer连接远程数据库
- LaTeX实战经验:如何插入程序代码
- git-如何在git上下载单个文件夹
- linux下安装或升级GCC 4.8以上版本(包括),以支持C++11
- matlab函数笔记
- [LeetCode
- metasploit魔鬼训练营第一章实践作业
- Error:Execution failed for task ':app:mergeDebugResources'. > Error: java.ut
- oracle 的sys 和 system 账号
- 栈的压入、弹出序列
- Member Function的调用方式
- BZOJ4864 [BeiJing 2017 Wc]神秘物质
- JavaWeb--Servlet过滤器Filter和SpringMVC的HandlerInterceptor(Session和Cookie登录认证)
- SuperMap Objects .NET 中更新方法的使用