Wednesday, 26 December 2012

Revese a number

Hi friends commonly  we  are using below program to reversing a number. but in some cases its wont work like reversing of 20 and 02. once check it by using below program.

class Program
    {
        static void Main(string[] args)
        {
            int n , b, sum=0;
            n = Convert.ToInt32(Console.ReadLine ());
            while (n > 0)
            {
                b = n % 10;
                sum = (sum * 10) + b;
                n = n / 10;
            }
            Console.WriteLine(sum);
            Console.ReadLine();
             }
    }

I think you find its wont work to reverse a numbers which are starting with zero '0' and ending a number with a Zero '0'.  so am suggesting to you  choose below program while they are asking to reverse a number.


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

namespace reverse_of_a_number
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, i;
            n = Convert.ToInt32(Console.ReadLine());
            string str = Convert.ToString(n); // converting int to string

           char[] arr = str.ToCharArray(); // converting string to array
           
           char[] arr1 = new char[arr.Length];
            // now reverse an array using for loop
            for (i = 0; i < arr.Length; i++)
            {
                arr1[arr.Length - 1 - i] = arr[i];
            }
            string result = new string(arr1); // converting an array to string
            Console.ReadLine();
        }
    }
}

NOTE:  1. For understanding purpose i added some unnecessary code.
             This program also have some mistakes Lts See who will finds it.
                                                  
                                                                          Thank You.

No comments:

Post a Comment