C# 如何将数字反转为整数而不是字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2040702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:55:03  来源:igfitidea点击:

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

c#algorithm

提问by Pritam Karmakar

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.

我遇到了一个问题“如何将数字反转为整数而不是字符串?” 有人可以帮我找出答案吗?反转应该反转数字的十进制数字,即使用基数 10。

采纳答案by jerjer

This should do it:

这应该这样做:

int n = 12345;
int left = n;
int rev = 0;
while(Convert.ToBoolean(left)) // instead of left>0 , to reverse signed numbers as well
{
   r = left % 10;   
   rev = rev * 10 + r;
   left = left / 10;  //left = Math.floor(left / 10); 
}

Console.WriteLine(rev);

回答by Brij

using System; 

public class DoWhileDemo {   
  public static void Main() { 
    int num; 
    int nextdigit; 

    num = 198; 

    Console.WriteLine("Number: " + num); 

    Console.Write("Number in reverse order: "); 

    do { 
      nextdigit = num % 10; 
      Console.Write(nextdigit); 
      num = num / 10; 
    } while(num > 0); 

    Console.WriteLine(); 
  }   
}

回答by cfern

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):

作为一个hackish one-liner(更新:使用本杰明的评论来缩短它):

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.

它不是单行的,因为我必须包含return 42;. C# 编译器不允许我编译,因为它认为没有代码路径返回值。

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

PS 如果你写出这样的代码并且你的同事发现了它,那么他/她对你所做的一切都是你应得的。被警告!

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

编辑:我想知道 LINQ one-liner 的速度有多慢,所以我使用了以下基准代码:

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):

结果(正整数范围内的 10^6 个随机数):

While loop version:
Operation took 279ms

Linq aggregate:
Operation took 984ms

回答by Stéphane

multiply it by -1? precise your question please...

乘以-1?请准确回答您的问题...

回答by Benjamin Podszun

Yay! A bling way. (No, really. I hope that this is more a "How would I do..." question and not something you really need in production)

好极了!一种金光闪闪的方式。(不,真的。我希望这更像是一个“我该怎么做……”的问题,而不是您在生产中真正需要的东西)

public int Reverse(int number) {
  return int.Parse(number.ToString().Reverse().Aggregate("", (s,c) => s+c));
}

回答by Alex Brown

You can't. Since the computer thinks in hexadecimal in any case, it is necessary for you to tokenise the number into Arabic format, which is semantically identical to the conversion to string.

你不能。由于计算机在任何情况下都以十六进制进行思考,因此您需要将数字标记为阿拉伯格式,这在语义上与转换为字符串相同。

回答by serhio

    /// <summary>
    /// Reverse a int using its sting representation.
    /// </summary>
    private int ReverseNumber(int value)
    {
        string textValue = value.ToString().TrimStart('-');

        char[] valueChars = textValue.ToCharArray();
        Array.Reverse(valueChars);
        string reversedValue = new string(valueChars);
        int reversedInt = int.Parse(reversedValue);

        if (value < 0)
           reversedInt *= -1;

        return reversedInt;
    }

回答by Rohit

Check below simple and easy -

检查以下简单易行-

public int reverseNumber(int Number)
{
  int ReverseNumber = 0;
  while(Number > 0)
  {
    ReverseNumber = (ReverseNumber * 10) + (Number % 10);
    Number = Number / 10;
  }
  return ReverseNumber;
}

Reference :Reverse number program in c#

参考:c#中的倒数程序

回答by Derrick

Old thread, but I did not see this variation:

旧线程,但我没有看到这种变化:

        int rev(int n) {
            string str = new String(n.ToString().Reverse().ToArray());
            return int.Parse(str);
        }

回答by Ousmane Loum

I looked at the following solution. But how about when n is negative?

我查看了以下解决方案。但是当 n 为负时呢?

Lets say n = -123456

假设 n = -123456

Here is a tweak I added to it to handle negative numbers, with that assumption it will threat negative numbs the same way.

这是我添加到它的一个调整来处理负数,假设它会以同样的方式威胁负数。

        int reverse = 0;
        bool isNegative = false;

        if (n < 0)
            isNegative = true;

        n = Math.Abs(n);
        while (n > 0)
        {
            int rem = n % 10;
            reverse = (reverse * 10) + rem;
            n = n / 10;
        }

        if (isNegative)
            reverse = reverse * (-1);

        return reverse;