首页 > 代码库 > CC150 2.4
CC150 2.4
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。