# 【leetcode】【java】【2、两数相加】

输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)



    //链表转int
public static int toInt(ListNode l){
int i = 1;
int val = l.val;
int res = i*val;
while(l.next!=null){
l = l.next;
val = l.val;
i=i*10;
res += i*val;
}
return res;
}

//int转链表
public static ListNode toListNode(int l){
int m = l%10;
int n = l/10;
ListNode res = new ListNode(m);
while(n>0){
m = n%10;
n = n/10;
ListNode node = new ListNode(m);
res.next = node;
res = node;
}
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int v1 = toInt(l1);
int v2 = toInt(l2);
int sum = v1 + v2;
}


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int m = 0; int n = 0;
ListNode tmp = new ListNode(-1);
while(l1!=null && l2!=null){
int v1 = l1.val;
int v2 = l2.val;
int res = v1 + v2 + n;
m = res%10;
n = res/10;
ListNode p = new ListNode(m);
tmp.next = p;
tmp = p;
l1 = l1.next;
l2 = l2.next;
}
while(l1!=null){
int res = l1.val + n;
m = res%10;
n = res/10;
ListNode p = new ListNode(m);
tmp.next = p;
tmp = p;
l1 = l1.next;
}
while(l2!=null){
int res = l2.val + n;
m = res%10;
n = res/10;
ListNode p = new ListNode(m);
tmp.next = p;
tmp = p;
l2 = l2.next;
}
if(n!=0){
ListNode p = new ListNode(1);
tmp.next = p;
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

透明的阿尔冯斯

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-18 484

11-05 1550
06-22 1014
07-03 325
04-05 329
01-14 1156
08-08 64
07-06 76
02-18 71
05-19
12-20
09-18