Introduction
In this article, we will talk about how to reverse a number in C#. This is an essential technical interview question that may be posed to beginner, intermediate, and experienced candidates.
We previously covered how to reverse a string in the last article,
Reverse Number in C#
Method 1. Let’s create a console application and write the below code in program.cs file.
Console.WriteLine("Enter a Number");
var number = Convert.ToInt32(Console.ReadLine());
int reverseNumber = 0;
while(number!=0)
{
var reminder = number % 10;
reverseNumber = (reverseNumber * 10) + reminder;
number = number / 10;
}
Console.WriteLine($"Reverse Number is: {reverseNumber}");
Console.ReadLine();
Output
Method 2. Let’s try same example with another approach but it is not recommended.
Console.WriteLine("Enter a Number");
var number = Console.ReadLine();
var reverseNumber = new string (number.Reverse().ToArray());
Console.WriteLine($"Reverse Number is: {Convert.ToInt32(reverseNumber)}");
Console.ReadLine();
Output
Hope you enjoy this article and learn something new.