Skip to content

Commit 37725d8

Browse files
authored
Enhance readme with Reverse Integer solution details
Added detailed explanation and implementation for the Reverse Integer problem in Java.
1 parent 64b603d commit 37725d8

File tree

1 file changed

+62
-1
lines changed
  • src/main/java/g0001_0100/s0007_reverse_integer

1 file changed

+62
-1
lines changed

src/main/java/g0001_0100/s0007_reverse_integer/readme.md

Lines changed: 62 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,65 @@ Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If rev
2626

2727
**Constraints:**
2828

29-
* <code>-2<sup>31</sup> <= x <= 2<sup>31</sup> - 1</code>
29+
* <code>-2<sup>31</sup> <= x <= 2<sup>31</sup> - 1</code>
30+
31+
To solve the Reverse Integer problem in Java using a `Solution` class, we'll follow these steps:
32+
33+
1. Define a `Solution` class with a method named `reverse`.
34+
2. Initialize variables to keep track of the reversed integer (`rev`), the sign of the input integer (`sign`), and the absolute value of the input integer (`x`).
35+
3. Iterate through each digit of the input integer `x`:
36+
- Extract the least significant digit using the modulo operator.
37+
- Update the reversed integer `rev` by multiplying it by 10 and adding the extracted digit.
38+
- Update `x` by removing the least significant digit using integer division.
39+
4. Check if the reversed integer `rev` overflows the signed 32-bit integer range. If so, return 0.
40+
5. Return the reversed integer `rev` with the appropriate sign.
41+
42+
Here's the implementation:
43+
44+
```java
45+
public class Solution {
46+
47+
public int reverse(int x) {
48+
int rev = 0;
49+
int sign = (x < 0) ? -1 : 1;
50+
int limit = Integer.MAX_VALUE / 10;
51+
int absX = Math.abs(x);
52+
53+
while (absX > 0) {
54+
int digit = absX % 10;
55+
absX /= 10;
56+
57+
if (rev > limit || (rev == limit && digit > 7)) {
58+
return 0;
59+
}
60+
61+
if (rev < -limit || (rev == -limit && digit < -8)) {
62+
return 0;
63+
}
64+
65+
rev = rev * 10 + digit;
66+
}
67+
68+
return rev * sign;
69+
}
70+
71+
public static void main(String[] args) {
72+
Solution solution = new Solution();
73+
74+
// Test cases
75+
int x1 = 123;
76+
System.out.println("Example 1 Output: " + solution.reverse(x1));
77+
78+
int x2 = -123;
79+
System.out.println("Example 2 Output: " + solution.reverse(x2));
80+
81+
int x3 = 120;
82+
System.out.println("Example 3 Output: " + solution.reverse(x3));
83+
84+
int x4 = 0;
85+
System.out.println("Example 4 Output: " + solution.reverse(x4));
86+
}
87+
}
88+
```
89+
90+
This implementation provides a solution to the Reverse Integer problem in Java.

0 commit comments

Comments
 (0)