Leetcode 7 Solution
This article provides solution to leetcode question 7 (reverse-integer)
Access this page by simply typing in "lcs 7" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/reverse-integer
Thinking Process
Nothing fancy. Just put all the digits into an array, and pop them back reversely.
Time & Space Complexity
Assuming N is the bit-length of the number
- Time complexity:
O(N)
- Space complexity:
O(N)
Solution
class Solution {
public:
int reverse(int x) {
vector<int> nums;
int64_t v = x;
while (v != 0)
{
nums.push_back(v % 10);
v /= 10;
}
for (auto it = nums.begin(); it != nums.end(); it++)
{
v = v * 10 + *it;
}
if (v > INT_MAX)
return 0;
else if (v < INT_MIN)
return 0;
else
return v;
}
};