1 题目
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
Linked List Math
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode headNode = new ListNode(0); ListNode p = headNode; int carry = 0; while (l1 != null && l2 != null) { int var = l1.val + l2.val + carry; carry = var / 10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l1 = l1.next; l2 = l2.next; } //要考虑到前面可能有进位,要加上carry while (l1 != null) { int var = l1.val + carry; carry = var /10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l1 = l1.next; } while (l2 != null) { int var = l2.val + carry; carry = var /10; var = var % 10; ListNode node = new ListNode(var); p.next = node; p = p.next; l2 = l2.next; } //要考虑到最后有个进位,就新建一个节点 if (carry != 0) { ListNode node = new ListNode(carry); p.next = node; p = p.next; } return headNode.next; } }
原文:http://www.cnblogs.com/lingtingvfengsheng/p/4396152.html