Today’s algorithm problem is to solve the "Integer Reversal" algorithm using C language. Below are my algorithm ideas and implementation. Let’s take a look.
Algorithm Problem
Given a 32-bit signed integer, reverse it.
Algorithm Idea
We will use a clever method to solve the integer reversal problem. The idea of the algorithm is to reverse the integer by continuously taking the integer's quotient and remainder.
The steps of the algorithm are as follows:
Define a variable result to store the reversed result.
Loop through the following steps until the given integer is 0:
- 
Take the last digit of the given integer (by taking the remainder of 10). 
- 
Add the last digit to result. 
- 
Divide the given integer by 10 and take the floor. 
Check if result overflows. If it overflows, return 0.
Return result.
👇 Click to receive 👇
👉 C Language Knowledge Resource Collection
Code Implementation
Below is an example code implementing the “Integer Reversal” algorithm in C language:
#include <stdio.h>
#include <limits.h>
int reverse(int x) {    int result = 0;
    while (x != 0) {        int digit = x % 10;        x /= 10;
        // Check for overflow        if (result > INT_MAX / 10 || (result == INT_MAX / 10 && digit > 7))            return 0;        if (result < INT_MIN / 10 || (result == INT_MIN / 10 && digit < -8))            return 0;
        result = result * 10 + digit;    }
    return result;}
int main() {    int num = 123;    int reversed = reverse(num);
    printf("Input: %d\n", num);    printf("Reversed: %d\n", reversed);
    return 0;}Algorithm Analysis
The time complexity of this algorithm is O(log(x)), where x is the number of digits in the given integer. In the loop, we divide the given integer by 10 each time, so the number of iterations depends on the number of digits in the given integer.
The space complexity is O(1).
Examples and Tests
Example Input 1:
Input: 123Example Output 1:
Reversed: 321Example Input 2:
Input: -123Example Output 2:
Reversed: -321Example Input 3:
Input: 120Example Output 3:
Reversed: 21Example Input 4:
Input: 1534236469Example Output 4:
Reversed: 0Conclusion
This article provides the code to solve the integer reversal algorithm problem using C language. By continuously taking the integer’s quotient and remainder, we can reverse the given integer. It is important to check for overflow conditions promptly. The time complexity of this algorithm is O(log(x)), and the space complexity is O(1).
 Programmer Technical Exchange Group
Programmer Technical Exchange Group
Scan the code to join the group and remember to note: city, nickname, and technical direction.