问题描述
比较字符串文字中包含的两个非常大的数字的最佳方法是什么?
例如,我想比较以下内容:
90000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000009
或
0000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 p>
在两种情况下,第二种显然都更大,但是如何在不迭代元素的情况下有效地找到它呢?
这是另一种解决方案:
public static int CompareNumbers(string x,y )
{
如果(x.Length> y.Length)y = y.PadLeft(x.Length,'0');
else if(y.Length&x.Length)x = x.PadLeft(y.Length,'0');
for(int i = 0; i< x.Length; i ++)
{
if(x [i]< y [i])返回-1;
如果(x [i]> y [i])返回1;
}
返回0;
}
What is the best way to compare two very large numbers contained in string literals?
For example I want to compare the followings:"90000000000000000000000000000000000000000000000000000000000000000000000000001""100000000000000000000000000000000000000000000000000000000000000000000000000009"
or
"0000000000111111111111111111111111111111111111111111111111111111111111111111""0000001111111111111111111111111111111111111111111111111111111111111111111111"
In both cases obviously the second one is greater, but how could I find it out efficiently without iterating on elements?
Here is another solution:
public static int CompareNumbers(string x, string y)
{
if (x.Length > y.Length) y = y.PadLeft(x.Length, '0');
else if (y.Length > x.Length) x = x.PadLeft(y.Length, '0');
for (int i = 0; i < x.Length; i++)
{
if (x[i] < y[i]) return -1;
if (x[i] > y[i]) return 1;
}
return 0;
}
这篇关于比较存储在字符串中的非常大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!