0
点赞
收藏
分享

微信扫一扫

LeetCode Top 100 Liked Questions 2.Add Two Numbers (Java版; Medium)


​​welcome to my blog​​

LeetCode Top 100 Liked Questions 2.Add Two Numbers (Java版; Medium)

题目描述

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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

第一次做; 没有考虑到两个数位数不同的情况, 也没考虑到最后carry为1还要再创建一个节点的情况; 好处是创建了一个节点作为伪头结点; 初始化 → (执行→更新)^n

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//input check
if(l1==null||l2==null)
return null;
//
ListNode head = new ListNode(0), curr = head;
int carry=0, sum=0;
while(l1!=null && l2!=null){
sum = (l1.val + l2.val + carry) % 10;
carry = (l1.val + l2.val + carry) / 10;
curr.next = new ListNode(sum);
//update
l1 = l1.next;
l2 = l2.next;
curr = curr.next;
}
//两个数字位数可能不同,所以还得单独来两个while循环
while(l1!=null){
sum = (l1.val + carry) % 10;
carry = (l1.val + carry) / 10;
curr.next = new ListNode(sum);
//update
l1 = l1.next;
curr = curr.next;
}
while(l2!=null){
sum = (l2.val + carry) % 10;
carry = (l2.val + carry) / 10;
curr.next = new ListNode(sum);
//update
l2 = l2.next;
curr = curr.next;
}
//细节!如果还有进位的话, 需要再创建一个节点
if(carry==1)
curr.next = new ListNode(1);

return head.next;
}
}


举报

相关推荐

0 条评论