Problem
https://leetcode.com/problems/reverse-integer/description/
Answer
class Solution {
public:
int reverse(int x) {
long long result = 0;
while(x) {
result = result * 10 + x % 10;
if (result > INT_MAX || result < INT_MIN) {
return 0;
}
x /= 10;
}
return result;
}
};
Let's examine the solution to the problem.
For an example, consider the following:
Input: x = -123
Output: -321
We solve the problem by taking the last digit in order.
Input: x = -123
1: -3
2: -32
3: -321
Output: -321
Now, let's dissect the code:
int reverse(int x) {
long long result = 0;
The long long result = 0
is used to store the answer. It might exceed the int range because we're reversing x
. Therefore, we use long long
.
while(x) {
result = result * 10 + x % 10;
As mentioned before, we solve the problem by taking the last digit in order.
We use x % 10
to get the last digit. The variable result
will have a value starting from the second iteration. We use result * 10
to shift the digits one place to the left as we add the new digit to the rightmost place.
x = -123
result = 0
Step 1: result = result * 10 + x % 10 = 0 * 10 + -123 % 10 = -3
x = -12 // explained later in this blog post.
result = -3
Step 2: result = result * 10 + x % 10 = - 3 * 10 + -12 % 10 = -32
x = -1
result = -32
Step 3: result = result * 10 + x % 10 = - 32 * 10 + -1 % 10 = -321
if (result > INT_MAX || result < INT_MIN) {
return 0;
}
If result
exceeds the range of int, we must return 0. The condition result > INT_MAX || result < INT_MIN
checks for that.
x /= 10;
We use x /= 10
to eliminate the last digit.
For instance,
x = - 123
Step 1:
x = -123
// result = 0
result = result * 10 + x % 10 = -3
Step 2:
x = -12
// result = -3
result = result * 10 + x % 10 = -3
We need to eliminate the rightmost digit, so we use x /= 10
to shift the digits one place to the right.
We continue this process until x
becomes 0.
Top comments (0)