Sunday, 7 September 2014

Add two large numbers that cannot be stored in numeric data types

You are given two numbers as String which are so large that it cannot be stored in any of the numeric data types. You need to return the sum of these numbers as String.

"it cannot be stored in any of the numeric data types" means it includes Long, BigDecimal etc.. Assume around 1000 digits in the number

package com.prasune.coding;

import java.util.Stack;

public class AddBigNumbers {

      public static void main(String[] args) {
            String number1 = "123456789129";
            String number2 = "345343";
            System.out.println(add(number1, number2));
      }

      public static String add(String number1, String number2){
            String result = "";
            Stack<Integer> n1 = new Stack<Integer>();
            Stack<Integer> n2 = new Stack<Integer>();
            Stack<Integer> sum = new Stack<Integer>();
            int carryForwardValue = 0;
            for (int i = 0; i < number1.length(); i++) {
                  n1.push(Integer.parseInt("" + number1.charAt(i)));
            }
            for (int i = 0; i < number2.length(); i++) {
                  n2.push(Integer.parseInt("" + number2.charAt(i)));
            }
            while(!n1.empty() || !n2.empty()){
                  int digit1 = 0;
                  int digit2 = 0;
                  if(!n1.empty()){
                        digit1 = n1.pop();
                  }
                  if(!n2.empty()){
                        digit2 = n2.pop();
                  }                
                  int sumOfNumbers = digit1 + digit2 + carryForwardValue;
                  sum.push(sumOfNumbers % 10);
                  carryForwardValue = sumOfNumbers/10;
            }
            while(!sum.empty()){
                  result = result + sum.pop();
            }
            return result;
      }
}



No comments:

Post a Comment