LeetCode之Reverse Integer
2017-03-24 15:23
330 查看
1、题目
Reverse digits of an integer.Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.
2、代码实现
代码实现1、通过不了LeetCode
public static int reverse(int x) { if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) { return 0; } boolean flag = false; //x是负数就是true,正数false if (x < 0) { flag = true; } String string = String.valueOf(x); String spliteStr = flag ? string.substring(1) : string; StringBuffer sb = new StringBuffer(spliteStr); sb = sb.reverse(); String result = sb.toString(); result = flag ? "-" + result : result; long value = Long.valueOf(result); if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) { return 0; } return (int)value; }
代码实现二、
通过不了LeetCode
public static int reverse1(int x) { if (x > Integer.MAX_VALUE || x < Integer.MIN_VALUE) { return 0; } long result = 0; int temp = Math.abs(x); while (temp > 0) { result *= 10; result = result + temp % 10; temp /= 10; } if (result > Integer.MAX_VALUE ||result<Integer.MIN_VALUE ) { return 0; } return (int)(x >= 0 ? result : -result); }
代码实现三
可以通过LeetCode
public static int reverse3(int n) { if (n > Integer.MAX_VALUE || n < Integer.MIN_VALUE) { return 0; } //输出结果定义为long long sum=0; while (n != 0) { int s = n % 10; sum = sum * 10 + s; n = n / 10; } //防止溢出操作 if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) { return 0; } return (int)sum; }
注意有溢出问题,对比分析,第一个实现和第二个实现 不越界没问题。
相关文章推荐
- LeetCode Reverse Integer
- LeetCode(7) Reverse Integer
- LeetCode Reverse Integer
- leetcode reverse Integer(反转整数)
- [leetcode] Reverse Integer 反转一个整数
- 【LeetCode 7: Reverse Integer】
- LeetCode | Reverse Integer(翻转整数)
- LeetCode-7-Reverse-Integer 水题
- leetcode Reverse Integer 007
- leetcode Reverse Integer 2.2 难度系数2
- leetcode第七题:Reverse Integer
- LEETCODE: Reverse Integer
- leetcode Reverse Integer
- Reverse Integer -- leetcode
- leetcode — reverse-integer
- LeetCode专栏L007_Reverse_Integer
- LeetCode 7 Reverse Integer(C,C++,Java,Python)
- 【leetcode】Reverse Integer(考虑溢出问题)
- Leetcode 7 Reverse Integer 将整数逆转
- LeetCode : Reverse Integer [java]