[Leetcode]2. 两数相加
题目描述
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
- 示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
- 示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
- 示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
本题考查链表相关知识。
java解法
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
static ListNode of(int[] nums) {
ListNode dummyHead = new ListNode(-1);
for (int i = nums.length - 1; i >= 0; i--) {
dummyHead.next = new ListNode(nums[i], dummyHead.next);
}
return dummyHead.next;
}
@Override
public String toString() {
ListNode cur = this;
StringBuilder buffer = new StringBuilder();
while (cur != null) {
buffer.append(cur.val).append("->");
cur = cur.next;
}
return buffer.toString();
}
}
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode curL1 = l1;
ListNode curL2 = l2;
//进位
int carry = 0;
ListNode dummyHead = new ListNode(-1);
ListNode cur = dummyHead;
while (curL1 != null || curL2 != null) {
int val1 = curL1 == null ? 0 : curL1.val;
int val2 = curL2 == null ? 0 : curL2.val;
int val = val1 + val2 + carry;
cur.next = new ListNode(val % 10);
carry = val / 10;
if (curL1 != null) {
curL1 = curL1.next;
}
if (curL2 != null) {
curL2 = curL2.next;
}
cur = cur.next;
}
if (carry == 1) {
cur.next = new ListNode(1);
}
return dummyHead.next;
}
public static void main(String[] args) {
ListNode l1 = ListNode.of(new int[]{9, 9, 9, 9, 9, 9, 9});
ListNode l2 = ListNode.of(new int[]{9, 9, 9, 9});
ListNode listNode = new Solution().addTwoNumbers(l1, l2);
System.out.println(l1);
System.out.println(l2);
System.out.println(listNode);
}
}