【LeetCode题解】7_反转整数
【LeetCode题解】7_反转整数
描述
给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123
输出: 321
示例 2:
输入: -123
输出: -321
示例 3:
输入: 120
输出: 21
注意:
假设我们的环境只能存储 32 位有符号整数,其数值范围是 \([-2^{31},\,2^{31} - 1]\)。根据这个假设,如果反转后的整数溢出,则返回 0。
方法一
思路
输入的整数除以 10 得到商和余数,接着将返回的结果(初始值为 0)乘以 10 加上得到的余数作为新的结果,最后判断结果是否溢出(大于 32 位整数的最大值或者小于 32 位整数的最小值),将商作为新的整数重复上述过程,如果商为 0 则程序结束。
可以将求整数逆序数的过程想象成两个栈之间的弹出和压入操作。一个整数的每一位数存放在栈的每一格中,最高位存放在栈底,最低位存放在栈顶。将栈 A 的栈顶弹出,压入栈 B 的栈底,重复上述过程直到栈 A 为空,此时就完成了求整数逆序数的功能。实际中,弹出和压入操作并不需要借助真正的栈,可以通过求余(数学运算)实现。
其实,Python 语言的整数类型的取值范围并不存在限制,因此更不存在所谓的溢出。
Java 实现
class Solution {
public int reverse(int x) {
long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
return 0;
}
}
return (int) result;
}
}
// Runtime: 23 ms
// Your runtime beats 77.34 % of java submissions.
复杂度分析:
- 时间复杂度:\(O(log(n))\)
- 空间复杂度:\(O(1)\)
类似的 Java 实现
class Solution {
public int reverse(int x) {
int ret = 0;
while (x != 0) {
int pop = x % 10;
if (ret > Integer.MAX_VALUE / 10 || (ret == Integer.MAX_VALUE / 10 && pop > 7)) {
return 0;
}
if (ret < Integer.MIN_VALUE / 10 || (ret == Integer.MIN_VALUE / 10 && pop < -8)) {
return 0;
}
ret = ret * 10 + pop;
x = x / 10;
}
return ret;
}
}
// Runtime: 21 ms
// Your runtime beats 99.21 % of java submissions.
复杂度分析同上。
Python 实现
class Solution:
def reverse(self, x):
"""
Arguments:
----------
x : int, the value range is [-2147483648, 2147483647]
Return:
-------
ret : int, the reverse order number
"""
rev, a = 0, abs(x)
while a:
rev = rev * 10 + a % 10
a = a // 10
if x > 0 and rev < 2**31:
return rev
elif x < 0 and rev <= 2**31:
return -rev
else:
return 0
# Runtime: 56 ms
# Your runtime beats 85.51 % of python3 submissions.
复杂度分析同上。
方法二:转化为求字符串的倒序
Java 实现
class Solution {
public int reverse(int x) {
if (x == 0) {
return 0;
}
boolean isPos = x > 0;
StringBuilder sb = new StringBuilder();
char[] chars = String.valueOf(x).toCharArray();
for (int i = chars.length - 1; i >= 0; --i) {
if (chars[i] == '0' && sb.length() == 0) {
continue;
}
if (chars[i] == '-') {
continue;
}
sb.append(chars[i]);
}
String xStr = null;
if (isPos) {
xStr = sb.toString();
} else {
xStr = "-" + sb.toString();
}
int rev;
try {
rev = Integer.valueOf(xStr);
} catch (Exception e) {
return 0;
}
return rev;
}
}
复杂度分析:
- 时间复杂度:\(O(log(n))\)
- 空间复杂度:\(O(1)\)
Python 实现
class Solution:
def reverse(self, x):
"""
Arguments:
----------
x : int, the value range is [-2147483648, 2147483647]
Return:
-------
ret : int, the reverse order number
"""
sign = [1, -1][x < 0]
rev = sign * int(str(abs(x))[::-1])
return rev if -2**31 <= rev <= 2**31 - 1 else 0
# Runtime: 76 ms
# Your runtime beats 42.26 % of python3 submissions.
复杂度分析同上。
【LeetCode题解】7_反转整数的更多相关文章
- [Leetcode] reverse integer 反转整数
Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to ...
- leetCode题解之反转字符串中的元音字母
1.问题描述 Reverse Vowels of a String Write a function that takes a string as input and reverse only the ...
- leetcode NO.7 反转整数 (python实现)
来源 https://leetcode-cn.com/problems/reverse-integer/description/ 题目描述 给定一个 32 位有符号整数,将整数中的数字进行反转. 示例 ...
- leetCode题解之反转二叉树
1.题目描述 经典的反转二叉树,就是将二叉树中每个节点的左.右儿子交换. 2.题目分析 3.代码 TreeNode* invertTree(TreeNode* root) { if(root == N ...
- [LeetCode题解]92. 反转链表 II | 一次遍历 + 反转
解题思路 将链表分为三部分:[0, m).[m, n].(n, L],其中 L 为链表长度. 第一步:使用虚拟头节点 dummy,用于将 head 也能参与操作: 第二步:找到第 m-1 节点(fir ...
- [LeetCode题解]206. 反转链表 | 迭代 + 递归
方法一:迭代 解题思路 遍历过程,同时反转,这里需要一个指针 pre 要保存前一个节点. 代码 /** * Definition for singly-linked list. * public cl ...
- C#版 - Leetcode 13. 罗马数字转整数 - 题解
C#版 - Leetcode 13. 罗马数字转整数 - 题解 Leetcode 13. Roman to Integer 在线提交: https://leetcode.com/problems/ro ...
- 【LeetCode题解】206_反转链表(Reverse-Linked-List)
目录 描述 解法一:迭代 思路 Java 实现 Python 实现 复杂度分析 解法二:递归 思路 Java 实现 Python 实现 复杂度分析 更多 LeetCode 题解笔记可以访问我的 git ...
- LeetCode 4.反转整数
给定一个 32 位有符号整数,将整数中的数字进行反转. 示例 1: 输入: 123 输出: 321 示例 2: 输入: -123 输出: -321 示例 3: 输入: 120 输出: 21 注意: ...
随机推荐
- pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
# 背景 安装pip后发现执行pip install pytest,提示下面错误 pip is configured with locations that require TLS/SSL, howe ...
- c# 前后日期设置
List<string> list = new List<string>(); //根据当月 显示前6个月 for(int i=0;i<6;i++) { list.add ...
- C++ 模板和 C# 泛型之间的区别(C# 编程指南)
C# 泛型和 C++ 模板都是用于提供参数化类型支持的语言功能. 然而,这两者之间存在许多差异. 在语法层面上,C# 泛型是实现参数化类型的更简单方法,不具有 C++ 模板的复杂性. 此外,C# 并不 ...
- C#递归例程
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- cnVCL的安装
cnVCL是cnpack组件中的不可视组件库,里面包含很多有用的组件,网址:http://www.cnpack.org/showdetail.php?id=739&lang=zh-cn 安装步 ...
- 【OCP-12c】CUUG 071题库考试原题及答案解析(15)
15.(6-24)choose the best answerExamine the structure of the MEMBERS table:You want to display detail ...
- 关于Mysql数据库进行多表查询时设计编程思想
SQL代码:
- Centos 7.x 安装配置tomcat-8过程梳理
----------注意CentOS7.x中的selinux和firewalld都关闭.而且一.二.三部分都是独立的,所以发现8081和8080端口时不要慌哦. 原创,朋友们转载时请著名出处. 一.安 ...
- ionic 项目 随笔
1,首先 会进入src/index.html, <!-- The polyfills js is generated during the build process --> <sc ...
- FutureTask与Fork/Join
在学习多线程的过程中,我们形成了一种思维习惯.那就是对于某个耗时操作不再做同步操作,让他分裂成一个线程之后执行下一步,而线程执行耗时操作.并且我们希望在我们需要它返回的时候再去调用它的结果集.好比我们 ...