【LeetCode】7. Reverse Integer
2018-03-26 11:26
513 查看
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法一:
注意数据范围是-2^32 ~ 2^32 - 1, Integer.MIN_VALUE ~ Integer.MAX_VALUE
代码如下:public int reverse(int x) {
long res = 0;
while (x != 0){
res = res * 10 + x % 10;
x /= 10;
}
return (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) ? 0 : (int) res;
}
解法二:
方法一样,但是不用定义long。If overflow exists, the new result will not equal previous one. (来源于LeetCode discussion)
代码如下:public int reverse(int x){
int result = 0;
while (x != 0){
int newResult = result * 10 + x % 10;
if ((newResult - x % 10) / 10 != result){
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法一:
注意数据范围是-2^32 ~ 2^32 - 1, Integer.MIN_VALUE ~ Integer.MAX_VALUE
代码如下:public int reverse(int x) {
long res = 0;
while (x != 0){
res = res * 10 + x % 10;
x /= 10;
}
return (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) ? 0 : (int) res;
}
解法二:
方法一样,但是不用定义long。If overflow exists, the new result will not equal previous one. (来源于LeetCode discussion)
代码如下:public int reverse(int x){
int result = 0;
while (x != 0){
int newResult = result * 10 + x % 10;
if ((newResult - x % 10) / 10 != result){
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}
相关文章推荐
- Leetcode:7. Reverse Integer
- LeetCode 7. Reverse Integer 倒序输出数字
- leetcode_7. Reverse Integer 反转整数的各个数字
- LeetCode 7. Reverse Integer (倒转数字)
- LeetCode---7. Reverse Integer
- LeetCode-7. Reverse Integer
- 小白笔记------------------------leetcode(7. Reverse Integer)
- [LeetCode] 7. Reverse Integer
- 【leetcode】7. Reverse Integer
- 7. Reverse Integer Leetcode Python
- leetcode 7. Reverse Integer
- [LeetCode-Java]7. Reverse Integer
- leetcode 7. Reverse Integer
- 【LeetCode】7. Reverse Integer
- LeetCode 7. Reverse Integer
- LeetCode7. Reverse Integer
- Leetcode 7. Reverse Integer
- leetcode 7. Reverse Integer
- leetcode:7. Reverse Integer
- 蜗牛慢慢爬 LeetCode 7. Reverse Integer [Difficulty: Easy]