首页 > 其他 > 详细

20.12.24 leetcode2

时间:2020-12-24 11:56:37      阅读:24      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/add-two-numbers/

题意:给你两个链表,每个链表都表示一个从后往前的十进制数,每个位都只容纳一个数字。

分析:构造一个新链表,每一位都是两个链表的对应位加上进位。

/**
 * Definition for singly-linked list.
 * 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; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head=null,tail=null;
        int carry=0;
        while(l1!=null||l2!=null){
            int n1 = l1!=null?l1.val:0;
            int n2 = l2!=null?l2.val:0;
            int sum = (n1+n2+carry)%10;
            if(head==null){
                head=tail= new ListNode(sum);
            }else{
                tail.next=new ListNode(sum);
                tail=tail.next;
            }
            if(l1!=null)l1=l1.next;
            if(l2!=null)l2=l2.next;
            carry=(n1+n2+carry)/10;
        }
        if(carry!=0)tail.next=new ListNode(carry);
        return head;
    }
}

 

20.12.24 leetcode2

原文:https://www.cnblogs.com/qingjiuling/p/14182910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!