美文网首页
Add Two Numbers

Add Two Numbers

作者: Wenyue_offer | 来源:发表于2017-09-12 11:04 被阅读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.

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8

    链接

    /**
     * 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 dummy = new ListNode(0);
            ListNode tmp = dummy, i = l1, j = l2;
           //carry 进位标志
            int carry = 0;
            
            while(i!=null || j != null){
                int sum = carry;
                // main program 运算
                sum += (i != null)? i.val:0;
                sum += (j != null)? j.val:0;
                
                // 更新状态
                tmp.next = new ListNode(sum%10);
                tmp = tmp.next;
                
                carry = sum/10;
                
                i = (i == null)?i:i.next;
                j = (j==null)?j:j.next;
            }
           // 最后一位还进位了,需要再添加个node
            if (carry !=0){
                tmp.next = new ListNode(carry);
            }
            return dummy.next;
        }
    }
    

    相关文章

      网友评论

          本文标题:Add Two Numbers

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