美文网首页
2. 两数相加(2019-01-12)

2. 两数相加(2019-01-12)

作者: Rondo9 | 来源:发表于2019-01-12 16:36 被阅读0次
    两数相加

    class Solution {

        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

            int carry = 0;

            ListNode temp = new ListNode(0);

            ListNode result = temp;

            while (l1 != null || l2 != null) {

                int sum = (l1 != null? l1.val: 0) + (l2 != null? l2.val: 0) + carry;

                carry = sum / 10; temp.next = new ListNode(sum % 10);

                l1 = l1 != null? l1.next: l1;

                l2 = l2 != null? l2.next: l2;

                temp = temp.next;

            }

            if (carry > 0) {

                temp.next = new ListNode(carry);

            }

            return result.next;

        }

    }

    相关文章

      网友评论

          本文标题:2. 两数相加(2019-01-12)

          本文链接:https://www.haomeiwen.com/subject/uxdcdqtx.html