LeetCode 7. Reverse Integer
2018-03-16 10:04
453 查看
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.
保留符号翻转数字,如果int溢出则返回0;用vector储存每一位数字,注意0的处理。对于溢出的判断我随便写了对符号进行判断没想到就ac了,不知道LeetCode的case覆盖全不全,这样做有没有问题。
class Solution {
public:
int reverse(int x) {
int f = 1;
if (x < 0) {
f = -1;
x = -x;
}
vector<int>v1;
while (x) {
int t = x % 10;
if((!v1.empty())||t)
v1.push_back(t);
x /= 10;
}
int i, ans = 0;
for (i = 0; i < v1.size(); i++)
{
ans += v1[i] * pow(10, v1.size() - i - 1);
}
ans *= f;
if (ans * f < 0) return 0;
return ans;
}
};
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.
保留符号翻转数字,如果int溢出则返回0;用vector储存每一位数字,注意0的处理。对于溢出的判断我随便写了对符号进行判断没想到就ac了,不知道LeetCode的case覆盖全不全,这样做有没有问题。
class Solution {
public:
int reverse(int x) {
int f = 1;
if (x < 0) {
f = -1;
x = -x;
}
vector<int>v1;
while (x) {
int t = x % 10;
if((!v1.empty())||t)
v1.push_back(t);
x /= 10;
}
int i, ans = 0;
for (i = 0; i < v1.size(); i++)
{
ans += v1[i] * pow(10, v1.size() - i - 1);
}
ans *= f;
if (ans * f < 0) return 0;
return ans;
}
};
相关文章推荐
- 【C语言】LeetCode 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
- python写算法题:leetcode: 7. Reverse Integer
- LeetCode 7. Reverse Integer 整数反转
- LeetCode 7. Reverse Integer 倒序输出数字
- leetcode_7. Reverse Integer 反转整数的各个数字
- leetcode--7. Reverse Integer
- Leetcode: 7. Reverse Integer(JAVA)
- leetcode--7. Reverse Integer
- [Leetcode从零开刷]7. Reverse Integer
- [Leetcode]7. Reverse Integer
- [LeetCode]7. Reverse Integer(自学留存)
- [Leetcode] 7. Reverse Integer