
Sponsored
This method involves extracting digits one at a time from the integer using modulus and division operations. By repeatedly taking the last digit of the number, you can construct the reversed integer. However, special care must be taken to handle the overflow condition, as reversing an integer can potentially produce a value beyond the 32-bit signed integer limit.
Time Complexity: O(log10(x)) because we are processing each digit once.
Space Complexity: O(1) since we are using constant extra space.
1using System;
2
3class ReverseInteger {
4 public static int Reverse(int x) {
5 int result = 0;
6 while (x != 0) {
7 int pop = x % 10;
8 x /= 10;
9 if (result > int.MaxValue / 10 || (result == int.MaxValue / 10 && pop > 7)) return 0;
10 if (result < int.MinValue / 10 || (result == int.MinValue / 10 && pop < -8)) return 0;
11 result = result * 10 + pop;
12 }
13 return result;
14 }
15
16 static void Main(string[] args) {
17 int x = 123;
18 Console.WriteLine(Reverse(x));
19 }
20}The solution in C# checks for overflow during each operation to avoid exceeding 32-bit integer limits, similar to C and Java.
In this approach, the integer is first converted to a string representation, reversed as a string, and then converted back to an integer. This method mitigates overflow issues by checking the integer post-conversion if it falls within the valid range.
Time Complexity: O(n) where n is the number of digits in x.
Space Complexity: O(n) due to the use of the string to store digits temporarily.
1function reverse(x) {
2 const sign
In this JavaScript implementation, the integer x is converted to a string and reversed using array methods. The potential 32-bit overflow is checked before returning the signed result.