leetcode: 2. Add Two Numbers

Difficulty

Medium

Description

/**
 * 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

class Solution {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	ListNode head = new ListNode(0);
    	ListNode t = head;
    	int sum = 0;
    	int var1, var2;
        while ((l1 != null)||(l2 != null)) {
        	if (l1 != null) {
        		var1 = l1.val;
        	} else {
        		var1 = 0;
        	}
        	if (l2 != null) {
        		var2 = l2.val;
        	} else {
        		var2 = 0;
        	}
        	sum = sum + var1 + var2;
        	if (sum > 9) {
        	    t.next = new ListNode(sum - 10);
        		sum = 1;     	
        	} else {
        		t.next = new ListNode(sum);
        		sum = 0;
        	}
            t = t.next;
    		if (l1 != null) {
            	l1 = l1.next;
    		}
            if (l2 != null) {
            	l2 = l2.next;
            }
        }
        if (sum == 1) {
        	t.next = new ListNode(1);
        }
        return head.next;
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/84961926
今日推荐