导航
导航

Leetcode-2. Add Two Numbers

题目

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.

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

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

boolean flag = false;

int v = l1.val + l2.val;

if(v > 9) {
//需要进位
flag = true;
}
ListNode head = new ListNode(v % 10);
ListNode n = head;


ListNode n1 = l1.next;
ListNode n2 = l2.next;

while(n1 != null || n2 != null || flag){
if(n1 == null){
n1 = new ListNode(0);
}
if(n2 == null){
n2 = new ListNode(0);
}

v = n1.val + n2.val;
if(flag){
v +=1;
flag = false;
}

if(v > 9) {
//需要进位
flag = true;
}
n.next = new ListNode(v % 10);
n = n.next;

n1 = n1.next;
n2 = n2.next;
}

return head;
}

数据结构

1
2
3
4
5
6
7
8
public class ListNode {
public int val;
public ListNode next;

public ListNode(int x) {
val = x;
}
}

总结

  • 多写几个例子研究规律;
  • 其实规律就是两个链接顺序节点做加法,进位向后一位进位;