
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.
1#include <stdio.h>
2#include <limits.h>
3
4int reverse(int x) {
5 int result = 0;
6 while (x != 0) {
7 int pop = x % 10;
8 x /= 10;
9 if (result > INT_MAX / 10 || (result == INT_MAX / 10 && pop > 7)) return 0;
10 if (result < INT_MIN / 10 || (result == INT_MIN / 10 && pop < -8)) return 0;
11 result = result * 10 + pop;
12 }
13 return result;
14}
15
16int main() {
17 int x = 123;
18 printf("%d", reverse(x));
19 return 0;
20}This C solution uses a while loop to pop digits from the input number x and push them onto the result. Overflow conditions are checked both before multiplication and addition.
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.