Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- //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.
- class AddsTwoPositiveNumbers
- {
- // Convert string to array
- static string[] InputElemOfStrToArray(string numStr)
- {
- string[] array = new string[numStr.Length];
- for (int i = 0; i < numStr.Length; i++)
- {
- array[i] = numStr[i].ToString();
- }
- return array;
- }
- // Collection of the two arrays by index
- private static string[] SumArrays(string[] firstArray, string[] secArray)
- {
- int currentSum = 0;
- string sumStr = " ";
- bool check = true;
- int remainder = 0;
- int maxLength = (firstArray.Length - 1);
- int minLength = (secArray.Length - 1);
- // Summation of the array in sumStr
- for (int i = maxLength, j = minLength; i >= 0; i--)
- {
- currentSum = (int.Parse(secArray[j]) + int.Parse(firstArray[i]));
- if (currentSum < 10)
- {
- sumStr += Convert.ToString(currentSum) + " ";
- }
- else
- {
- remainder = currentSum % 10;
- sumStr += Convert.ToString(remainder) + " ";
- if (i > 0)
- { // If we have remainder increase nex elem with one
- int increase = (int.Parse(firstArray[i - 1]) + 1);
- firstArray[i - 1] = increase.ToString();
- }
- else
- {
- sumStr += 1;
- }
- }
- // Modeling 'j'
- if ((j >= 0) && check)
- {
- if (j == 0)
- {
- secArray[j] = "0";
- check = false;
- j++; // Stop out of range exept.
- }
- j--;
- }
- }
- string[] unnecessaryElements = new string[] {" "}; // Remove empty spaces in array
- string[] SplitSumStrArr = sumStr.Split( unnecessaryElements,StringSplitOptions.RemoveEmptyEntries );
- Array.Reverse(SplitSumStrArr); // Reverse array SplitSumArr
- return SplitSumStrArr;
- }
- static void Main(string[] args)
- {
- string[] firstArray;
- string[] secArray;
- Console.WriteLine("Enter the first integer");
- string firstNum = Console.ReadLine();
- Console.WriteLine("Enter the second integer");
- string secNum = Console.ReadLine();
- // Most larger number adds to firstArray
- if (firstNum.Length > secNum.Length)
- {
- firstArray = InputElemOfStrToArray(firstNum);
- secArray = InputElemOfStrToArray(secNum);
- }
- else
- {
- firstArray = InputElemOfStrToArray(secNum);
- secArray = InputElemOfStrToArray(firstNum);
- }
- string[] arraySum = SumArrays(firstArray, secArray);
- Console.WriteLine(string.Join("", arraySum));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement