C# 中更简单的大加法器?

发布于 2024-08-02 14:46:46 字数 1920 浏览 4 评论 0原文

我刚刚在学校接到了写一个大加法器的任务。意思是一种可以将非常大的数字组合在一起的方法。 我们有 10 分钟的时间,我确实按时完成了。老师批准了。

但我对结果不太满意,我想我可能采取了错误的方法。

这是我的版本:

using System;
using System.Text;

namespace kæmpe_adder
{
    static class Program
    {
        static void Main()
        {
            var x = "1111";
            var y = "111111111";

            Console.WriteLine(BigAdder(x, y));
            Console.ReadLine();
        }
        public static StringBuilder BigAdder(string x, string y)
        {
            var a = new StringBuilder(x);
            var b = new StringBuilder(y);
            return BigAdder(a, b);
        }
        public static StringBuilder BigAdder(StringBuilder x, StringBuilder y)
        {
            int biggest;
            int carry = 0;
            int sum;
            var stringSum = new StringBuilder();

            if (x.Length > y.Length)
            {
                y.FillString(x.Length - y.Length);
                biggest = x.Length;
            }
            else if (y.Length > x.Length)
            {
                x.FillString(y.Length - x.Length);
                biggest = y.Length;
            }
            else
            {
                biggest = y.Length;
            }

            for (int i = biggest - 1; i >= 0; i--)
            {
                sum = Convert.ToInt32(x[i].ToString()) + Convert.ToInt32(y[i].ToString()) + carry;
                carry = sum / 10;
                stringSum.Insert(0, sum % 10);
            }

            if (carry != 0)
            {
                stringSum.Insert(0, carry);
            }

            return stringSum;
        }
        public static void FillString(this StringBuilder str, int max)
        {
            for (int i = 0; i < max; i++)
            {
                str.Insert(0, "0");
            }
        }
    }
}

当我编写它时,我想到了如何使用二进制文件来实现它。

有没有更短和/或更简单的方法来做到这一点?

I just had the task in school to write a big adder. Meaning a method that can put very large numbers together.
We had 10 minutes and I did complete it on time. The teacher approved it.

I am not too satisfied with the result though, and I thought I perhaps were taking the wrong approach.

Here is my version:

using System;
using System.Text;

namespace kæmpe_adder
{
    static class Program
    {
        static void Main()
        {
            var x = "1111";
            var y = "111111111";

            Console.WriteLine(BigAdder(x, y));
            Console.ReadLine();
        }
        public static StringBuilder BigAdder(string x, string y)
        {
            var a = new StringBuilder(x);
            var b = new StringBuilder(y);
            return BigAdder(a, b);
        }
        public static StringBuilder BigAdder(StringBuilder x, StringBuilder y)
        {
            int biggest;
            int carry = 0;
            int sum;
            var stringSum = new StringBuilder();

            if (x.Length > y.Length)
            {
                y.FillString(x.Length - y.Length);
                biggest = x.Length;
            }
            else if (y.Length > x.Length)
            {
                x.FillString(y.Length - x.Length);
                biggest = y.Length;
            }
            else
            {
                biggest = y.Length;
            }

            for (int i = biggest - 1; i >= 0; i--)
            {
                sum = Convert.ToInt32(x[i].ToString()) + Convert.ToInt32(y[i].ToString()) + carry;
                carry = sum / 10;
                stringSum.Insert(0, sum % 10);
            }

            if (carry != 0)
            {
                stringSum.Insert(0, carry);
            }

            return stringSum;
        }
        public static void FillString(this StringBuilder str, int max)
        {
            for (int i = 0; i < max; i++)
            {
                str.Insert(0, "0");
            }
        }
    }
}

When I wrote it, I thought of how you do it with binaries.

Is there a shorter and/or perhaps simpler way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

深海少女心 2024-08-09 14:46:46

从代数的角度来看,您的代码看起来是正确的。从设计的角度来看,您肯定更愿意将每个大数字封装在一个类中,这样您就不必一直引用字符串/字符串构建器。我也不太喜欢这种 FillString 方法,在两个数字都有非零值时添加数字似乎更合理,然后将进位添加到更大的数字,直到完成。

不确定关于二进制文件的问题是什么?正常长度数字(32 位和 64 位)由 CPU 作为单个操作进行添加。

From the algebraic point of view your code looks correct. From the design point of view, you would definitely prefer to encapsulate each of these big numbers in a class, so that you don't have to reference the string/string builders all the time. I am also not a big fan of this FillString approach, it seems more reasonable to add the digits while both numbers have non-zero values, and then just add the carry to the bigger number until you are done.

Not sure what was the question about binaries? The normal length numbers (32bit and 64bit) are added by the CPU as a single operation.

灯角 2024-08-09 14:46:46

您可以从许多开源实现中获取灵感。

http://www.codeproject.com/KB/cs/biginteger.aspx

http://biginteger.codeplex.com/

一般来说,我建议使用字节数组或long 以获得最佳性能,但从字符串到数组的转换将是不平凡的。

以相反的顺序存储数字;这使得寻找同等的地方变得微不足道。

这使得添加不同大小的字符串数字变得更加容易:

int place = 0;
整数进位=0;

while (地方<较短.长度){
    result.Append(AddDigits(更长[地方],更短[地方],引用进位));
    ++地点;
}

while (地方<更长.长度){
    result.Append(AddDigits(longer[place], 0, ref进位));
    ++地点;
}

if ( 进位 != 0 )
    result.Append(carry.ToString());

There are a number of open source implementations you could look to for inspiration.

http://www.codeproject.com/KB/cs/biginteger.aspx

http://biginteger.codeplex.com/

In general, I would recommend using an array of byte or long for best performance, but the conversion from a string to the array would be non-trivial.

Store the numbers in reverse order; this makes finding equivalent places trivial.

This makes it easier to add differently sized strings numbers:

int place = 0;
int carry = 0;

while ( place < shorter.Length ) {
    result.Append (AddDigits (longer[place], shorter[place], ref carry));
    ++place;
}

while ( place < longer.Length ) {
    result.Append (AddDigits (longer[place], 0, ref carry));
    ++place;
}

if ( carry != 0 )
    result.Append (carry.ToString ());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文