Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Numerics;
- namespace _08.AddNumbers
- {
- class Program
- {
- // Write a method that adds two positive integer numbers represented as arrays of digits
- // (each array element arr[i] contains a digit; the last digit is kept in arr[0]).
- // Each of the numbers that will be added could have up to 10 000 digits.
- static BigInteger addArraysOfDigits(int[] arr1, int[] arr2)
- {
- int maxLen = arr1.Length > arr2.Length ? arr1.Length:arr2.Length;
- int[] tempArr = new int[maxLen + 1];
- int[] sum = new int[maxLen + 1];
- if (arr1.Length > arr2.Length)
- {
- for (int i = 0; i < maxLen; i++)
- {
- if (i < arr2.Length)
- {
- tempArr[i] = arr2[i];
- }
- else
- {
- tempArr[i] = 0;
- }
- }
- for (int i = 0; i < sum.Length; i++)
- {
- if (i < arr1.Length)
- {
- sum[i] = (arr1[i] + tempArr[i]) % 10;
- }
- if (i > 0 && arr1[i - 1] + tempArr[i - 1] >= 10)
- {
- sum[i] += 1;
- }
- //Console.Write(sum[i] + ", ");
- }
- }
- else
- {
- for (int i = 0; i < maxLen; i++)
- {
- if (i < arr1.Length)
- {
- tempArr[i] = arr1[i];
- }
- else
- {
- tempArr[i] = 0;
- }
- }
- for (int i = 0; i < sum.Length; i++)
- {
- if (i < arr2.Length)
- {
- sum[i] = (arr2[i] + tempArr[i]) % 10;
- }
- if (i > 0 && arr2[i - 1] + tempArr[i - 1] >= 10)
- {
- sum[i] += 1;
- }
- //Console.Write(sum[i] + ", ");
- }
- }
- string resultString = "";
- for (int i = sum.Length - 1; i >= 0; i--)
- {
- resultString += sum[i];
- }
- BigInteger result = BigInteger.Parse(resultString);
- return result;
- }
- static void Main(string[] args)
- {
- int[] arr1 = {9, 1, 1, 1};
- int[] arr2 = {9, 2, 3, 9};
- BigInteger result = addArraysOfDigits(arr1, arr2);
- Console.WriteLine(result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement