Solved

C# Reverse int in fast ways

Posted on 2016-11-15
6
42 Views
Last Modified: 2016-11-16
i have been looking for a way to reverse an integer and i have found this

while(left>0)
{
  r = left % 10;
  rev = rev * 10 + r;
  left = left / 10;
}

Open in new window

but the problem is this code is extremely slow. because it will only be a very small part of big operation.
so i tried to code it myself and i have been to this
string[] userinput = Console.ReadLine().Split(' ');
			int i = int.Parse(userinput[0]);
			int j = int.Parse(userinput[1]);
			int k = int.Parse(userinput[2]);
			int Reverse = 0;
			char[] temp;
			string trans = i.ToString();
			temp = trans.ToCharArray();
			temp.Reverse();
			trans = new string(temp);
			Reverse = int.Parse(trans);
			Console.WriteLine(Reverse);

Open in new window

but it always gives the value 0 "about the j and k forget about them its just for the rest of my code" so can anyone help me how can i make it work and if this can't be done any new ways to how to make it in quicker way than the shown above because it's really extremely slow.
0
Comment
Question by:Omar Alaa
  • 3
  • 2
6 Comments
 
LVL 33

Expert Comment

by:ste5an
ID: 41888858
Can you explain your need for this operation?

Cause "reverse an int" in our given context depends on the format (base). E.g. 0xef is also an int. What is its "reverse" value? It seems to depend on the base..

So your loop maybe already the fastest way to do it in .NET.

Caveat: an int could be lesser then 0, then your code does not work.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 41888904
Didn't get the task...
0
 

Author Comment

by:Omar Alaa
ID: 41888908
I meant for example if the int value is 5273 i want it to be 3725
0
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 41888934
You method would be VERY slow compare to what you have at the beginning. In your own method you operate with string and character, it much-much slower than division and multiplication  operations.

I just tried to measure time. To reverse all numbers from 0 to 999999 (one million operations) it took 80 - 90 milliseconds!
With printing these results it took up to half a minute.

namespace Reverser
{
    class Program
    {
        static void Main(string[] args)
        {
            var watch = System.Diagnostics.Stopwatch.StartNew();
            for (int i = 0; i < 1000000; i++)
            {
                int r = reverse(i);
                // Console.WriteLine(r); // Printing makes it much longer!!!- 
            }
            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Console.WriteLine("Elapsed ms: " + elapsedMs);
                Console.ReadLine();
        }

        private static int reverse(int input)
        {
            int result = 0;
            int current = 0;
            int toReverse = Math.Abs(input);
            int sign = (input == 0)?1:input/toReverse;

            while (toReverse > 0)
            {
                current = toReverse % 10;
                result = result * 10 + current;
                toReverse = toReverse / 10;
            }


            return result*sign;
        }
    }
}

Open in new window

0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 500 total points
ID: 41888944
OK, I tried your code:
        private static int reverse2(int input)
        {
            int Reverse = 0;
            char[] temp;
            string trans = input.ToString();
            temp = trans.ToCharArray();
            temp.Reverse();
            trans = new string(temp);
            Reverse = int.Parse(trans);


            return Reverse;
        }

Open in new window


It takes nearly three-four times worse result for numbers from 0 to 999999. Not too bad but still slower.
I don't really think you can make it faster than initial code.
0
 

Author Closing Comment

by:Omar Alaa
ID: 41889492
Okay. Thanks to letting me know that :D
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
About delegates in c sharp 3 47
C#.NET and microsoft certification. 3 40
Install Problem 13 29
SqlDependency to get update from sql to my c# app 2 39
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question