Sponsored Ad

Tuesday, January 11, 2011

Efficient Way to Reverse Numbers in C#

So you would like to reverse the numbers using C#. You can treat the number as a string and directly reverse the number but here is another way to reverse it.  and this on the basis of mathematical formula. The program is given below.

Efficient Way to Reverse Numbers in C#

using System;
using System.Collections;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int iNumber = 450;
            int rev = 0, iLength = iNumber.ToString().Length;
            for (int i = 0; i <iLength; i++)
            {
                rev *= 10;
                rev += (iNumber % 10);
                iNumber /= 10;
            }
            Console.Write(rev.ToString());
            Console.ReadLine();
        }    
    }
}

2 comments:

  1. Console.WriteLine(int.Parse(string.Join("", 450.ToString().Reverse())));

    ReplyDelete

Sponsored Ad

Website Update

Followers