Solved

C# Reverse int in fast ways

Posted on 2016-11-15
6
28 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 32

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 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

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now