我遇到了一个问题“如何将数字反转为整数而不是字符串?”谁能帮我找出答案?反转应该反转数字的小数位,即使用基数 10。
最佳答案
是这样的吗?
public int ReverseInt(int num)
{
int result=0;
while (num>0)
{
result = result*10 + num%10;
num /= 10;
}
return result;
}
作为一个 hackish one-liner(更新:使用 Benjamin 的评论来缩短它):
num.ToString().Reverse().Aggregate(0, (b, x) => 10 * b + x - '0');
更快的一又四分之一类轮:
public static int ReverseOneLiner(int num)
{
for (int result=0;; result = result * 10 + num % 10, num /= 10) if(num==0) return result;
return 42;
}
这不是单行代码,因为我必须包括 return 42;
。 C# 编译器不允许我编译,因为它认为没有代码路径返回值。
附言如果你写了这样的代码并且同事发现了它,那么他/她对你所做的一切都是你应得的。警告!
编辑:我想知道 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);
}
结果(正 int32 范围内的 10^6 个随机数):
While loop version:
Operation took 279ms
Linq aggregate:
Operation took 984ms
关于c# - 如何将数字反转为整数而不是字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2040702/