题目
https://leetcode-cn.com/problems/add-two-numbers/description/
代码
/*
* @lc app=leetcode.cn id=2 lang=java
*
* [2] 两数相加
*/
// @lc code=start
/**
* Definition for singly-linked list. public class ListNode { int val; ListNode
* next; ListNode(int x) { val = x; } }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = new ListNode(-1);
ListNode head = p;
int add = 0;
while (l1 != null && l2 != null) {
int vv = l1.val + l2.val + add;
if (vv >= 10) {
add = 1;
vv = vv - 10;
} else {
add = 0;
}
ListNode newNode = new ListNode(vv);
p.next = newNode;
p = p.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode temp = l1 != null ? l1 : l2;
while (temp != null) {
int vv = temp.val + add;
if (vv >= 10) {
add = 1;
vv = vv - 10;
} else {
add = 0;
}
ListNode newNode = new ListNode(vv);
p.next = newNode;
p = p.next;
temp = temp.next;
}
if (add == 1) {
ListNode newNode = new ListNode(1);
p.next = newNode;
p = p.next;
}
return head.next;
}
}
// @lc code=end
网友评论