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?