-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoNumber.java
More file actions
89 lines (77 loc) · 1.87 KB
/
Copy pathAddTwoNumber.java
File metadata and controls
89 lines (77 loc) · 1.87 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.wgcris.LeetcodeAlgorithm;
import java.util.*;
/*
* 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
*/
public class AddTwoNumber {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode l1 = new ListNode(3);
ListNode x2 = new ListNode(6);
ListNode x3 = new ListNode(9);
l1.next=x2;
x2.next=x3;
ListNode l2 = new ListNode(2);
ListNode y2 = new ListNode(5);
ListNode y3 = new ListNode(8);
l2.next=y2;
y2.next=y3;
ListNode ret = addTwoNumber(l1,l2);
System.out.println(ret.next.val+" "+ret.next.next.val+" "+ret.next.next.next.val+" "+ret.next.next.next.next.val
);
}
public static ListNode addTwoNumber(ListNode n1,ListNode n2){
ListNode result=null;
ListNode t1 =n1;
ListNode t2 =n2;
ListNode t3 =new ListNode(0);
result =t3;
//进位符
int flag =0;
//如果两个链表都不为空
while(t1!=null&&t2!=null){
t3.next = new ListNode((t1.val+t2.val+flag)%10);
flag =(t1.val+t2.val+flag)/10;
t1=t1.next;
t2=t2.next;
t3 =t3.next;
}
while(t1!=null){
t3.next =new ListNode((t1.val+flag)%10);
flag =(t1.val+flag)/10;
t1=t1.next;
t3 =t3.next;
}
while(t2!=null){
t3.next =new ListNode((t2.val+flag)%10);
flag =(t2.val+flag)/10;
t2=t2.next;
t3 =t3.next;
}
while(flag!=0){
t3.next =new ListNode((flag%10));
flag =flag/10;
t3=t3.next;
}
t3.next=null;
return result;
}
}
class ListNode{
int val;
ListNode next;
public ListNode(int x){
val =x;
next=null;
}
public ListNode() {
// TODO Auto-generated constructor stub
}
}