Problem: Reverse an Integer with Overflow Handling
Goal:
Given an integer, reverse its digits. However, we must handle potential overflow, which occurs when the reversed integer exceeds the maximum or minimum value allowed for a 32-bit signed integer.
- 32-bit signed integer range:
- Minimum value:
-2147483648
- Maximum value:
2147483647
- Minimum value:
Steps:
- Extract the last digit of the number using modulus (
% 10
). - Remove the last digit of the number by dividing it by 10 (
/ 10
). - Append the extracted digit to the reversed number.
- Before appending the digit, check if the reversed number would overflow after the operation.
- If overflow is detected, return 0 (indicating an overflow).
Solution:
#include <stdio.h>
#define MY_INT_MIN -2147483648
#define MY_INT_MAX 2147483647
int reverseNumber(int num) {
int reversed = 0;
// While there are digits left to process
while (num != 0) {
// Extract the last digit of the number
int digit = num % 10;
num /= 10; // Remove the last digit from the number
// Check for overflow before updating the reversed number
if (reversed > (MY_INT_MAX / 10) || reversed < (MY_INT_MIN / 10)) {
return 0; // Return 0 if overflow is detected
}
// Update the reversed number by adding the extracted digit
reversed = digit + reversed * 10;
}
return reversed; // Return the reversed number
}
int main() {
int num = 2147483647; // Test input
printf("Reversed number: %dn", reverseNumber(num)); // Output the result
return 0;
}
Explanation of the Code:
-
Variable Initialization:
reversed
: Stores the reversed number.MY_INT_MIN
andMY_INT_MAX
: Constants that hold the minimum and maximum values for a 32-bit signed integer.
-
Reversal Logic:
- Extract the last digit (
digit = num % 10
). - Remove the last digit from
num
(num /= 10
). - Before updating the
reversed
number, check if the new value would cause overflow:- If
reversed
is greater thanMY_INT_MAX / 10
, adding a digit would overflow. - If
reversed
is less thanMY_INT_MIN / 10
, multiplyingreversed
by 10 would underflow.
- If
- If overflow is detected, return 0.
- Extract the last digit (
-
Main Function:
- Tests the function with an input number (
2147483647
), which is the maximum value for a 32-bit signed integer.
- Tests the function with an input number (
Output:
If the number can be reversed without overflow, the reversed value will be printed. Otherwise, 0
will be printed if there is overflow.
This solution efficiently checks for overflow and ensures that the reversal of large numbers is handled safely.