Reverse Integer(leetcode7)
2017-08-09 15:17
357 查看
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.
解题思路:通过对x%10不断得到当前x最后一位的数字,加到反转后的数字当中,最后再判断一下是否超出范围就可以了。借助了一个long型局部变量有点投机取巧。
discuss高赞答案,无须long型局部变量,加多一个判断语句即可检查是否超出范围,非常巧妙。
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.
解题思路:通过对x%10不断得到当前x最后一位的数字,加到反转后的数字当中,最后再判断一下是否超出范围就可以了。借助了一个long型局部变量有点投机取巧。
public class Solution { public int reverse(int x) { int count = 0; //记录已经操作的位数 long reverseNum = 0; //反转后的数 while (x != 0) { reverseNum = x % 10 + (reverseNum * 10); x /= 10; count++; if (count == 10) //判断是否超过32位整数的范围 if (reverseNum >= Integer.MAX_VALUE || reverseNum < Integer.MIN_VALUE) return 0; } return (int)reverseNum; } }
discuss高赞答案,无须long型局部变量,加多一个判断语句即可检查是否超出范围,非常巧妙。
public int reverse(int x) { int result = 0; while (x != 0) { int tail = x % 10; int newResult = result * 10 + tail; if ((newResult - tail) / 10 != result) { return 0; } result = newResult; x = x / 10; } return result; }
相关文章推荐
- LeetCode 7 :Reverse Integer ---- 反转int整数
- LeetCode Reverse Integer
- LeetCode: Reverse Integer
- Leetcode Reverse Integer
- leetcode: Reverse Integer
- leetcode——Reverse Integer
- leetcode — reverse-integer
- [LeetCode] Reverse Integer 解题报告
- [leetcode 7] Reverse Integer(整数反转) c函数实现
- LeetCode专栏L007_Reverse_Integer
- 《leetCode》:Reverse Integer
- leetcode reverse Integer(反转整数)
- LeetCode Reverse Integer
- LeetCode Reverse Integer
- [LeetCode]Reverse Integer解题报告
- leetcode---Reverse Integer
- 【python】【leetcode】【算法题目7—Reverse Integer】
- LeetCode Reverse Integer
- Reverse Integer | LeetCode
- LeetCode 7 — Reverse Integer(C++ Java Python)