Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

c# - How to reverse a number as an integer and not as a string?

I came across a question "How can one reverse a number as an integer and not as a string?" Could anyone please help me to find out the answer? Reversal should reverse the decimal digits of the number, i.e. use base 10.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this?

public int ReverseInt(int num)
{
    int result=0;
    while (num>0) 
    {
       result = result*10 + num%10;
       num /= 10;
    }
    return result;
}

As a hackish one-liner (update: used Benjamin's comment to shorten it):

num.ToString().Reverse().Aggregate(0, (b, x) => 10 * b + x - '0');

A speedier one-and-a-quarter-liner:

public static int ReverseOneLiner(int num)
{
    for (int result=0;; result = result * 10 + num % 10, num /= 10) if(num==0) return result;
    return 42;
}

It's not a one-liner because I had to include return 42;. The C# compiler wouldn't let me compile because it thought that no code path returned a value.

P.S. If you write code like this and a co-worker catches it, you deserve everything he/she does to you. Be warned!

EDIT: I wondered about how much slower the LINQ one-liner is, so I used the following benchmark code:

public static void Bench(Func<int,int> myFunc, int repeat)
{
    var R = new System.Random();
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (int i = 0; i < repeat; i++)
    {
        var ignore = myFunc(R.Next());
    }
    sw.Stop();
    Console.WriteLine("Operation took {0}ms", sw.ElapsedMilliseconds);
}

Result (10^6 random numbers in positive int32 range):

While loop version:
Operation took 279ms

Linq aggregate:
Operation took 984ms

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...