其他分享
首页 > 其他分享> > 两数相加代码实现

两数相加代码实现

作者:互联网

上代码:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode();
        ListNode ln = head;
        ListNode ln1 = l1;
        ListNode ln2 = l2;
        int carry = 0;
        while(ln1 != null || ln2 != null){
            int val1 = (ln1 == null ? 0 : ln1.val);
            int val2 = (ln2 == null ? 0 : ln2.val);
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            sum = sum % 10;
            ln.next=new ListNode(sum);
            if (ln1 != null){
                ln1 = ln1.next;
            }
            if(ln2 != null){
                ln2 = ln2.next;
            }
            ln = ln.next;
        }
        if (carry == 1) {
            ln.next = new ListNode(carry);
        }
        return head.next;
    }

 

标签:ListNode,实现,相加,ln1,ln2,next,carry,null,代码
来源: https://www.cnblogs.com/lhr123/p/16468552.html