Integer Reversal in C#

Given an integer, reverse digits of the Integer!

Converting Number to String

At first glance, integer reversal seems an easy problem. Turn the number to a string and reverse the string. However, you need to handle not only positive integers but also negative integers. Also, if the integers end in zeros when you flip it, the zeros should disappear.

In C#, ToString() method converts the numeric value to its equivalent string representation. At this point, we turned the integer into a string. However, to deal with negative integers, we use Math.ABS() method to get the absolute value of the integer and then convert it to a string.

I am already explained some different ways to reverse strings. Here, we use Array.Reverse() method on it. The return type of the function needs to be an integer. The int.Parse() method converts string to an integer in C#.

But, we need to handle the negative sign. The Math.Sign() method returns an integer that specify the sign of the number. If the value is less than zero, Math.Sign() returns -1, if the value is equal to zero it returns 0, otherwise, it returns 1. We can multiply the result of the parse method by Math.Sign() and pass the input value to it.

public static int ReverseInteger(int number)
{
    var str = Math.Abs(number).ToString().ToCharArray();
    Array.Reverse(str);
    return int.Parse(str) * Math.Sign(number);
}
Without Converting Integer to String

We can reverse an integer without converting the integer to a string. To do that, we can use remainder operator % to find the last digit of an integer and division operator / to remove the last digit.

public static int ReverseInteger(int number)
{
    var sign = Math.Sign(number);
    var reverse = 0;
    while (number > 0)
    {
        // Find the last digit.
        reverse = reverse * 10 + number % 10;

        // Remove the last digit.
        number /= 10;
    }

    return reverse * sign;
}

You can download the source code on Github.