C# Program to Reverse Integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Required Knowledge:

Checking Edge Cases:

Checking the edge cases is crucial in programming world. We have to return 0, when the reversed integer exceeds Int32.MaxValue( 231 − 1) or Int32.MinValue( −231 ).

Consider the example,

number = 123

reversedNumber = 321

This is easy one. We can easily reverse this number.

Consider the below tricky example,

number = 2147483647

reversedNumber = 0

Because the reversedNumber is 7463847421. This is ultimately higher than the Int32.MaxValue, so we need to return 0 in this case.

number = -2147483648

reversedNumber = 0

Because the reversedNumber is -8463847421 . This is extremely lower than the Int32.MinValue, so we need to return 0 in this case.

Efficient Solution

C# Program:

    class ReverseInteger
        static void Main()
            //Input to get the number as 32 bit integer
            int number = Convert.ToInt32(Console.ReadLine());

            int reversedNumber = 0;

            while(number != 0)
                int lastDigit = number % 10;
                int newReversedNumber = reversedNumber * 10 + lastDigit;

                //Checking this condition to find overflows
                if((newReversedNumber - lastDigit)/10 != reversedNumber)

                reversedNumber = newReversedNumber;

                number = number / 10;

Program Explanation

Whenever i mention, overflow condition, (newReversedNumber – lastDigit)/10  is equal with  reversedNumber, so no problem

Please take note and trace the values, then only you can improve your skills in programming.

The best way to learn programming is we must practice to trace the output values, how the values are forming.

Thanks for reading😊.

If you like this article, please subscribe this blog and share it with your friends.

Leave a Comment

Your email address will not be published. Required fields are marked *