Add Two Numbers

2017-09-12  本文已影响0人  Wenyue_offer

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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读