Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Collections.Generic;
- namespace SumOfTwoStrings
- {
- class Program
- {
- static void Main(string[] args)
- {
- TestSum();
- }
- private static void TestSum()
- {
- string num1 = "123456";
- string num2 = "12";
- string result = CalculateSumWithoutParsing(num1, num2);
- Console.WriteLine(result);
- string num3 = "12";
- string num4 = "123456";
- string secondResult = CalculateSumWithoutParsing(num3, num4);
- Console.WriteLine(secondResult);
- string num5 = "123456";
- string num6 = "123456";
- string thirdResult = CalculateSumWithoutParsing(num5, num6);
- Console.WriteLine(thirdResult);
- string num7 = "123454";
- string num8 = "123454";
- string fourthResult = CalculateSumWithoutParsing(num7, num8);
- Console.WriteLine(fourthResult);
- string num9 = "0";
- string num10 = "0";
- string fifthResult = CalculateSumWithoutParsing(num9, num10);
- Console.WriteLine(fifthResult);
- }
- private static string CalculateSumWithoutParsing(string num1, string num2)
- {
- var firstStack = new Stack<char>(num1);
- var secondStack = new Stack<char>(num2);
- string result = string.Empty;
- int carry = 0;
- while (firstStack.Count > 0 && secondStack.Count > 0)
- {
- char currentDigitFromFirstStack = firstStack.Pop();
- char currentDigitFromSecondStack = secondStack.Pop();
- int currentSum = int.Parse(currentDigitFromFirstStack.ToString()) + int.Parse(currentDigitFromSecondStack.ToString());
- int newCurrentResult = currentSum + carry; // if already have carry added it
- carry = 0;
- if (newCurrentResult / 10 > 0) // check for the carry after newCurrentResult
- {
- carry += newCurrentResult / 10;
- }
- result += (newCurrentResult % 10).ToString();
- }
- string finalResult = string.Empty;
- if (firstStack.Count == 0 && secondStack.Count > 0)
- {
- finalResult = GenereteFinalResult(secondStack, result, carry);
- }
- else if (secondStack.Count == 0 && firstStack.Count > 0)
- {
- finalResult = GenereteFinalResult(firstStack, result, carry);
- }
- else // the count of the both stecks is equal
- {
- finalResult = new String(result.ToCharArray().Reverse().ToArray());
- }
- return finalResult.Trim();
- }
- private static string GenereteFinalResult(Stack<char> secondStack, string result, int carry)
- {
- string finalResult;
- char currentDigitFromSecondStack = secondStack.Pop();
- int newCurrentResult = int.Parse(currentDigitFromSecondStack.ToString()) + carry;
- string temporaryResult = result + newCurrentResult;
- string reverseTemporaryResult = new String(temporaryResult.ToCharArray().Reverse().ToArray());
- finalResult = string.Join("", secondStack.ToArray().Reverse()) + reverseTemporaryResult; // how to reverse string in a one line
- return finalResult;
- }
- }
- }
Add Comment
Please, Sign In to add comment