美文网首页
2. Add Two Numbers

2. Add Two Numbers

作者: 与你若只如初见v | 来源:发表于2018-05-23 17:16 被阅读0次

    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.

    Solution

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode t1 = l1, t2 = l2, r = new ListNode(0);
            ListNode now = r;
            boolean f = false;
            while(t1 != null || t2 != null){
                int sum = 0;
                sum += (t1 != null) ? t1.val : 0;
                sum += (t2 != null) ? t2.val : 0;
                if(f == true){
                    sum += 1;
                    f = false;
                }
                if(sum / 10 != 0){f = true;}
                ListNode node = new ListNode(sum % 10);
                now.next = node;
                now = node;
                if(t1 != null){t1 = t1.next;}
                if(t2 != null){t2 = t2.next;}
            }
            if(f == true){
                ListNode node = new ListNode(1);
                now.next = node;
            }
            return r.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:2. Add Two Numbers

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