Reverse Integer code in C++ with condition

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes
value to go outside the signed 32-bit integer range [-231, 231 – 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Explore Free Engineering Handwritten Notes!

Looking for comprehensive study materials on Python, Data Structures and Algorithms (DSA), Object-Oriented Programming (OOPs), Java, Software Testing, and more?

We earn a commission if you make a purchase, at no additional cost to you.
class Solution {
public:
    int reverse(int x) {
    int ans = 0;
    while( x != 0) {
       int digit x % 10;
         if( (ans > INT_MAX/10) 11 (ans < INT_MIN/10)) {
          return 0;
}
      ans = (ans* 10) + digit;
      x = x / 10;
}
     return ans;
}
};

This program takes an integer input from the user and stores it in variable n.

Then the while loop is iterated until n != 0 is false.

In each iteration, the remainder when the value of n is divided by 10 is calculated, reversed_number is computed and the value of n is decreased 10 fold.

This condition helps you to get 100% error-free code and bound the condition of 32 signed bit.

if( (ans > INT_MAX/10) 11 (ans < INT_MIN/10))

Let us see this process in greater detail:

nn != 0remainderreversed_number
2345true50 * 10 + 5 = 5
234true45 * 10 + 4 = 54
23true354 * 10 + 3 = 543
2true2543 * 10 + 2 = 5432
0falseLoop terminates.

Finally, reversed_number (which contains the reversed number) is printed on the screen

Leave a Reply