C# Examples

C# Program - Reverse digits of a given Integer



In C#, the reverse of a given integer can be found out by using below mentioned methods.

Method 1: Using iteration

The method involves the following steps:

Input: MyNum
Step 1: Initialize the RevNum = 0
Step 2: Iterate over MyNum while it is greater than zero.
   Step 2a: Calculate remainder of MuNum / 10
   Step 2b: Update RevNum by RevNum * 10 + remainder
   Step 2c: Update MyNum by MyNum / 10
Step 3: Return RevNum

Example:

Input: 564

RevNum: 0
Iteration 1: 
    Remainder: 564 % 10 = 4
    RevNum: 0 * 10 + 4 = 4
    MyNum: 564 / 10 = 56

Iteration 2: 
    Remainder: 56 % 10 = 6
    RevNum: 4 * 10 + 6 = 46
    MyNum: 56 / 10 = 5

Iteration 3: 
    Remainder: 5 % 10 = 5
    RevNum: 46 * 10 + 5 = 465
    MyNum: 5 / 10 = 0

return RevNum = 465

The below block of code shows the implementation of above concept:

using System;
 
class MyProgram {

  static int reverse(int MyNum) {    
    int RevNum = 0;
    int remainder;

    while(MyNum > 0){
      remainder = MyNum % 10;
      MyNum = MyNum / 10;
      RevNum = RevNum * 10 + remainder;
    }
    return RevNum;
  }  

  static void Main(string[] args) {
    int x = 1285;
    int y = 4567;
    Console.WriteLine("Reverse of {0} is: {1}", x, reverse(x));
    Console.WriteLine("Reverse of {0} is: {1}", y, reverse(y));
  }
}

The above code will give the following output:

Reverse of 1285 is: 5821
Reverse of 4567 is: 7654

Method 2: Using Recursion

The above result can also be achieved using recursive function:

using System;
 
class MyProgram {
  static int RevNum = 0;
  static int BaseVal = 1;
  
  static int reverse(int MyNum) {
    if(MyNum > 0) {
      reverse(MyNum/10);
      RevNum += MyNum % 10 * BaseVal;
      BaseVal *= 10;
    }
    return RevNum;
  }  

  static void Main(string[] args) {
    int x = 7902;
    Console.WriteLine("Reverse of {0} is: {1}", x, reverse(x));
  }
}

The above code will give the following output:

Reverse of 7902 is: 2097




5