LeetCode刷题(C++)——Reverse Integer(Easy)
2017-05-01 21:35
501 查看
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
class Solution {
public:
int reverse(int x) {
const int max = INT_MAX;
const int min = INT_MIN;
long sum = 0;
while(x)
{
int temp = x%10;
sum = sum*10+temp;
if(sum>max||sum<min)
return 0;
x = x/10;
}
return sum;
}
};
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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.
class Solution {
public:
int reverse(int x) {
const int max = INT_MAX;
const int min = INT_MIN;
long sum = 0;
while(x)
{
int temp = x%10;
sum = sum*10+temp;
if(sum>max||sum<min)
return 0;
x = x/10;
}
return sum;
}
};
相关文章推荐
- 【LeetCode】(7)Reverse Integer(Easy)
- leetcode_206_Reverse Linked List(easy)(C++)
- leetcode_07_Reverse Integer (easy)
- LeetCode 7 — Reverse Integer(C++ Java Python)
- LeetCode : 7 Reverse Integer C++
- LeetCode-7-Reverse Integer(Nmber-Strng)-Easy
- LeetCode Reverse Integer C++
- 【Leetcode】Reverse Integer(easy)
- [C++]LeetCode 7:Reverse Integer(翻转整数)
- LeetCode 7 Reverse Integer ( C++ )
- Leetcode_Reverse Integer[easy]
- LeetCode刷题(C++)——Roman to Integer(Easy)
- LeetCode每日一练(7) Reverse Integer C++版
- LeetCode 第7题 Reverse Integer (easy)——python
- leetcode 7 Reverse Integer C++
- leetcode_13_Roman to Integer(C++)(easy)
- 【Leetcode-easy】Reverse Integer
- LeetCode 之 Reverse Integer — C++ 实现
- LeetCode (Easy Part) Reverse Integer
- [leetcode]Reverse Integer 代码(C++)