Tuesday, June 19, 2012

Add two integer arrays

Consider the problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an .n C 1/-element array C. State the problem formally and write pseudocode for adding the two integers.

package com.webspherenotes.algo;

public class AddTwoIntegers {

  /**
   * @param args
   */
  public static void main(String[] args) {
    int[] first = {9,9,9,9};
    int[] second = {9,9,9,9};
    
    AddTwoIntegers addTwoInteger = new AddTwoIntegers();
    addTwoInteger.printArray(addTwoInteger.add(first, second));
    
  }

  
  private int[] add(int[] first, int[] second){
    int length = first.length;
    int[] result = new int[length+1];
    int carry = 0 ;
    for(int i = length -1 ; i >=0 ; i--){
      int currentValue = first[i] + second[i] + carry;
      result[i+1] = currentValue %10;
      carry = currentValue/10;
      printArray(result);
    }
    result[0]=carry;
    return result;
  }
  
  private void printArray(int[] input) {

    System.out.print("{");
    for (int i = 0; i < input.length; i++) {
      System.out.print(input[i]);
      if (i != input.length - 1)
        System.out.print(" , ");
    }
    System.out.println("}");
  }

}

No comments:

Post a Comment