Description
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
输入为两个非空链表代表两个非负的整数。这些整数以逆序的形式存储,并且每个元素包含一个一位数。将这两个整数相加得到一个新的链表并返回。
可以假定两个整数没有前导0,除了整数0本身。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
samples
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
用链表运算来表示加法,即342+465=807
Solutions
<ol>
<li> O(n)
// com.cnsumi.leetcode.algorithms. A0002_Add_Two_Numbers.java;
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
ret.append("(");
ListNode node = this;
do {
if (node != this) {
ret.append("->");
}
ret.append(node.val);
node = node.next;
} while (node != null);
ret.append(")");
return ret.toString();
}
}
public class A0002_Add_Two_Numbers {
public static void main(String[] args) {
ListNode l1 = new ListNode(2);
l1.next = new ListNode(4);
l1.next.next = new ListNode(3);
ListNode l2 = new ListNode(5);
l2.next = new ListNode(6);
l2.next.next = new ListNode(4);
System.out.println(l1);
System.out.println(l2);
System.out.println(solution1(l1, l2));
}
public static ListNode solution1(ListNode l1, ListNode l2) {
int carry = 0;
ListNode head = new ListNode(0);
ListNode pre = head;
while (l1 != null || l2 != null || carry > 0) {
int sum = (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val) + carry;
carry = sum / 10;
pre.next = new ListNode(sum % 10);
pre = pre.next;
l1 = l1 == null ? l1 : l1.next;
l2 = l2 == null ? l2 : l2.next;
}
return head.next;
}
}