Sunday, 31 May 2015

Reverse a integer with out casting the values in C#

In this post we are going to see how to reverse a integer with out casting the values, you can ask why we need this kind of 10 lines of code to do rather than two of casting and reverse the string, Normally Casting takes huge performance issue, for small operation it doesn't see as Big , for Big operations it Hit the performance of the applications.

Here we are 
1. Initialize a variable result with 0;
2.  Diving and module a value with 10, 
3. Assign the quotient to value to reset the original value
4. Then the result of module is added with previous operation result and multiply by 10.
4.  loop the process 2 to 4 until the quotient 0

Program.cs

            int num = 123456;
            num = Algorithm.ReverseInteger(num);


Output : now num value is 654321

Logic :
        public static int ReverseInteger(int value)
        {
            if(value<0)
            return value;

            int result = 0;
           
            while(true){
                Tuple<int,int> temp = CheckModule(value);
                value = temp.Item1;
                if(temp.Item1==0){
                  result =  result+temp.Item2;
                    break;
                }
                else
                    result = (result + temp.Item2 ) * 10;
            }
            return result;
        }


        private static Tuple<int, int> CheckModule(int value)
        {
            return Tuple.Create<int, int>(value / 10, value % 10);
        }      
    

From this post you can see how to reverse a string with out casting.

No comments:

Post a Comment