【LeetCode算法-7】Reverse Integer
2023-09-14 09:00:41 时间
LeetCode第7题:
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解题思路:
假如:x=1234,y=0
1)y乘以10,x把末位4移除掉,加给y(x=123,y=4)
2)y乘以10,x把末位3移除掉,加给y(x=12,y=43)
3)y乘以10,x把末位2移除掉,加给y(x=1,y=432)
4)y乘以10,x把末位1移除掉,加给y(x=0,y=4321)
代码:
int y = 0;
while(x/10!=0){
y*=10;
y+=x%10;
x/=10;
}
y=y*10 +x;
结果报错
原因是int的范围是-2147483647~2147483648
leetcode给的input是1534236469,倒转之后是9646324351,导致溢出了。所以要加上溢出判断
最后的代码
class Solution {
public int reverse(int x) {
int negative = 1;
if(x <= Integer.MIN_VALUE)
return 0;
if(x < 0){
x = -x;
negative = -1;
}
long y = 0;
while(x/10!=0){
y*=10;
y+=x%10;
x/=10;
}
y=y*10 +x;
if(y > Integer.MAX_VALUE)
return 0;
else
return (int)y * negative;
}
}
这也是很坑啊,溢出就输出0,鬼知道啊
相关文章
- leetcode 之Sum系列(七)
- Java实现 LeetCode 623 在二叉树中增加一行(遍历树)
- Java实现 LeetCode 606 根据二叉树创建字符串(遍历树)
- Java实现 LeetCode 587 安装栅栏(图算法转换成数学问题)
- Java实现 LeetCode 561 数组拆分 I(通过排序算法改写PS:难搞)
- Java实现 LeetCode 561 数组拆分 I(通过排序算法改写PS:难搞)
- Java实现 LeetCode 382 链表随机节点
- Java实现 LeetCode 343 整数拆分(动态规划入门经典)
- Java实现 LeetCode 21 合并两个有序链表
- Java实现LeetCode_0026_RemoveDuplicatesFromSortedArray
- 【刷题】【LeetCode】000-十大经典排序算法
- 【LeetCode算法-21】Merge Two Sorted Lists
- 【LeetCode算法-14】Longest Common Prefix
- 【LeetCode算法-13】Roman to Integer
- 【刷题】【LeetCode】000-十大经典排序算法
- 【LeetCode算法-53】Maximum Subarray
- 【LeetCode算法-38】Count and Say
- 【LeetCode算法-27】Remove Element
- 【LeetCode算法-26】Remove Duplicates from Sorted Array
- Python 刷Leetcode题库,顺带学英语单词(27)
- leetcode 226. 翻转二叉树
- leetcode算法第9题
- leetcode算法第5题
- leetcode算法第二题python答案
- 【LeetCode-面试算法经典-Java实现】【008-String to Integer (atoi) (字符串转成整数)】
- [LeetCode] 647. 回文子串 ☆☆☆(最长子串、动态规划、中心扩展算法)
- LeetCode Implement strStr()(Sunday算法)
- LeetCode 48 Anagrams
- 【Leetcode刷题Python】改进的算法,高效求一个数的因子