title: Calculating the Sum of values in a linked list
body: <p>I got a programming question at an interview recently. </p>
  
  <p>There are 2 linked lists. Each node stores a value from 1 through 9 (indicating one index of the number). Hence 123 would be a linked list 1->2->3</p>
  
  <p>The task was to create a function:</p>
  
  <p><code>static LinkedListNode getSum(LinkedListNode a, LinkedListNode b)</code> </p>
  
  <p>that would return the sum of the values in the 2 linked list arguements.</p>
  
  <p>If the array a is: 1->2->3->4</p>
  
  <p>And the array b is: 5->6->7->8</p>
  
  <p>The answer should be: 6->9->1->2</p>
  
  <p>Here is my algorithm:</p>
  
  <p>Go through each node in a and b, get the values as an integer and add them. Create a new linked list with the those values.</p>
  
  <p>Here is the code: It runs with a complexity of O(n) roughly I assume. Once through each of the array inputs and once to create the output array.</p>
  
  <p><strong>Any improvements? Better algorithms... or code improvements</strong></p>
  
  <pre><code>public class LinkedListNode {
          LinkedListNode next;
          int value;
  
      public LinkedListNode(int value) {
          this.value = value;
          this.next = null;
      }
  
      static int getValue(LinkedListNode node) {
          int value = node.value;
          while (node.next != null) {
              node = node.next;
              value = value * 10 + node.value;
          }
          return value;
      }
  
      static LinkedListNode getSum(LinkedListNode a, LinkedListNode b) {
          LinkedListNode answer = new LinkedListNode(0);
          LinkedListNode ans = answer;
          int aval = getValue(a);
          int bval = getValue(b);
          int result = aval + bval;
          while (result &gt; 0) {
              int len = (int) Math.pow((double) 10,
                      (double) String.valueOf(result).length() - 1);
              int val = result / len;
              ans.next = new LinkedListNode(val);
              ans = ans.next;
              result = result - val*len;
              }    
          return answer.next;
      }
  }
  </code></pre>