[LeetCode]Reverse Integer
来源:互联网 发布:淘宝店铺免费流量 编辑:程序博客网 时间:2024/06/03 17:04
Description:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
个人拙见:这道题比较简单,只是需要注意几个特殊情况的处理就可以了。以下是两种还不错的解法。
solution1:
public class Solution { public int reverse(int x) { int result = 0; while(x!=0) { int temp = x%10; int newResult = result*10+temp; //用来判断是否超出int范围 if((newResult-temp)/10!=result){return 0;} result = newResult; x /= 10; } return result; }}
solution2
public class Solution { public int reverse(int x) { long result = 0; while(x!=0) { long temp = x%10; result = result*10+temp; //用来判断是否超出int范围 if(result > Integer.MAX_VALUE){return 0;} if(result < Integer.MIN_VALUE){return 0;} x /= 10; } return (int)result; }}
- LeetCode:Reverse Integer
- LeetCode: Reverse Integer
- [Leetcode] Reverse Integer
- LeetCode : Reverse Integer
- [LeetCode] Reverse Integer
- Leetcode: Reverse Integer
- LeetCode 7 - Reverse Integer
- leetcode 104: Reverse Integer
- Leetcode : Reverse Integer
- 【leetcode】Reverse Integer
- [LeetCode]Reverse Integer
- LeetCode-Reverse Integer
- [leetcode] Reverse Integer
- LeetCode - Reverse Integer
- leetcode之Reverse Integer
- LeetCode | Reverse Integer
- LeetCode: Reverse Integer
- Leetcode: Reverse Integer
- IntelliJ IDEA开发Spark、打JAR包
- 2017 word finnal i Secret Chamber at Mount Rushmore
- 核心语法及函数
- 人人学点编程001-简单了解编程语言
- 2017 world final e Need for Speed
- [LeetCode]Reverse Integer
- linux实战应用~redis安装
- Codeforces #206(Div.1) C. Vasya and Beautiful Arrays
- JavaScript常用语法——函数(基础)
- Android 发版的小工具
- 常用排序算法-希尔排序
- html画红心
- JavaScript基础(二)
- _CrtIsValidHeapPointer