首页 > 其他 > 详细

CC150 2.4

时间:2014-11-24 08:42:32      阅读:249      评论:0      收藏:0      [点我收藏+]

2.4 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list. EXAMPLE Input: (3 -> 1 -> 5) + (5 -> 9 -> 2) Output: 8 -> 0 -> 8


Keep 2 pointers.

Node addUp(Node a, Node b)
{
  Node toReturn = null;
  Node last = null;
  
  boolean shift = false;
  while (a != null || b != null)
  {
      int result = 0;
      if (a != null)
      {
        if (a > 9 || a < 0)
          throw new IllegalArgumentExeption();
          
        result += a.data;
        a = a.next;
      }
      
      if (b != null)
      {
        if (a > 9 || a < 0)
          throw new IllegalArgumentExeption();
          
        result += b.data;
        b = b.next;
      }
      
      if (shift)
        result++;
    
      if (result > 9)
      {
        shift = true;
        result = a % 10;
      }
      else
        shift = false;
        
      Node newNode = new Node(result);
      if (last != null)
      {
        last.next = newNode;
      }
      last = newNode;
        
      if (toReturn == null)
        toReturn = newNode;  
  }
  
  return toReturn;    
}


CC150 2.4

原文:http://7371901.blog.51cto.com/7361901/1581732

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!