比较存储在字符串中的非常大的数字 [英] Compare very large numbers stored in string

查看:142
本文介绍了比较存储在字符串中的非常大的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较字符串文字中包含的两个非常大的数字的最佳方法是什么?



例如,我想比较以下内容:
90000000000000000000000000000000000000000000000000000000000000000000000000000000000000001
100000000000000000000000000000000000000000000000000000000000000000000000000000000000000009





0000000000111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111 p>

在两种情况下,第二种显然都更大,但是如何在不迭代元素的情况下有效地找到它呢?

解决方案

这是另一种解决方案:

  public static int CompareNumbers(string x,y )
{
如果(x.Length> y.L​​ength)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;
    }

这篇关于比较存储在字符串中的非常大的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆