How to find the reverse of a number using C# ?

Published on May 14, 2014 by abundantcode

Filed under C#

Last modified May 26, 2014

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4896 times

Below is a sample code snippet that demonstrates how to find the reverse of a number using C# .

How to find the reverse of a number using C# ?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AbundantcodeConsoleApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // How to find the reverse of a number using C# ?
            int Input = 2985;
            int ReverseNumber = 0;
            while (Input > 0)
            {
                int rem = Input % 10;
                ReverseNumber = (ReverseNumber * 10) + rem;
                Input = Input / 10;

            }
            Console.WriteLine("Output : {0}", ReverseNumber);
            Console.ReadKey();
        }
    }

    
}

1

3 Comments

  1. Brian Gilner

    Or you could be a linq-fanatic and implement in a one-liner:

    private static void Main(string[] args)
    {
    Func LinqReverse = x => x.ToString().Reverse().Aggregate(0, (a, c) => a * 10 + (c – ‘0’));
    Console.WriteLine(LinqReverse(123456));
    Console.ReadKey();
    }

    May 24, 2014 - 5:55 am – Reply

    • Brian Gilner

      Actually: Func LinqReverse = x => x.ToString().Reverse().Aggregate(0, (a, c) => c – ‘0’ + 10 * a);

      March 15, 2015 - 12:23 am – Reply

  2. Brian Gilner

    Or this:

    Func LinqReverse = x => Convert.ToInt32(string.Join(string.Empty, x.ToString().Reverse()));

    March 15, 2015 - 12:12 am – Reply

Leave a Comment


x

You might be Interested in these Posts

How to download a file from a URL using C#?

You can use the WebClient class in C# to download a file. How to download a file from a URL using C...

How to Create an Empty array without defining the size in C# ?

When we create an array in C# , we tend to define the size of the array as shown below. String[] st...

C++ Program to display "Hello, World!"

Problem Write a program in C++ to display "Hello, World!" on the screen. C++ Program to...