LeetCode_Add Two Numbers

来源:互联网 发布:淘宝集市c店免费活动 编辑:程序博客网 时间:2024/06/05 20:27

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解题思路:此题为左边低位,右边高位,逢十进一,所以直接遍历链表,求和求进位即可。如果是左边高位,右边低位那就呵呵了。

class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}public class AddTwoNumbers {public ListNode addTwoNumbers(ListNode l1, ListNode l2) {ListNode tmpNode = new ListNode(0);int carry = 0;carry = (l1.val + l2.val) / 10;// 求值,即进位tmpNode.val = (l1.val + l2.val) % 10;// 求模,即余数ListNode ln = new ListNode(tmpNode.val);ln = tmpNode;while (l1 != null && l1.next != null || l2 != null && l2.next != null) {int l1Value = 0;int l2Value = 0;if (l1 == null) {l1Value = 0;} else {l1 = l1.next;if (l1 != null)l1Value = l1.val;}if (l2 == null) {l2Value = 0;} else {l2 = l2.next;if (l2 != null)l2Value = l2.val;}int nextValue = (l1Value + l2Value + carry) % 10;int nextCarry = (l1Value + l2Value + carry) / 10;ListNode newLn = new ListNode(nextValue);carry = nextCarry;tmpNode.next = newLn;tmpNode = newLn;}if (carry > 0) {ListNode newLn = new ListNode(carry);tmpNode.next = newLn;}return ln;}public static void main(String[] args) {AddTwoNumbers solution = new AddTwoNumbers();ListNode node1 = new ListNode(5);// ListNode node2 = new ListNode(4);// ListNode node3 = new ListNode(3);// node1.next = node2;// node2.next = node3;ListNode node4 = new ListNode(5);// ListNode node5 = new ListNode(6);// ListNode node6 = new ListNode(4);// node4.next = node5;// node5.next = node6;ListNode resultNode = solution.addTwoNumbers(node1, node4);while (resultNode != null) {System.out.println(resultNode.val);resultNode = resultNode.next;}}}



0 0
原创粉丝点击