Following method is useful to reverse a number in C#. Call it in a class under Main method for execution.
int ReverseNumber(int number)
{
int reversed = 0;
int digit = 0;
while (number != 0)
{
digit = number % 10;
reversed = reversed * 10 + digit;
number = number/10;
}
return reversed;
}
Explanation: When a number is passed to the ReverseNumber method, we initialize two variables: reversed (to store the reversed number) and digit (to hold the last digit during each iteration), both set to zero initially.
We then use a loop that continues as long as the number is not zero. Inside the loop:
- We extract the last digit of the number by using the modulus operator (
number % 10) and assign it to thedigitvariable. - We update the
reversedvariable by multiplying its current value by 10 and adding the extracteddigit. This effectively shifts the digits ofreversedto the left and appends the new digit at the end. - We remove the last digit from the original number by dividing it by 10 (
number / 10) and assigning the result back tonumber. This discards the digit we just processed.
This process repeats until the number becomes zero. At that point, the loop exits and the method returns the reversed variable, which now holds the digits of the original number in reverse order.
Sample number: 123 Result: 321