Add Two Numbers

题目:http://oj.leetcode.com/problems/add-two-numbers/

You are given two linked lists representing two non-negative numbers. 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.

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; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    	ListNode head = null;
    	ListNode res = null;
        int a = 0;
        while (l1!=null || l2!=null) {
        	int sum = a;
        	if (l1!=null) {
        		sum += l1.val;
        		l1 = l1.next;
        	}
        	if (l2!=null) {
        		sum += l2.val;
        		l2 = l2.next;
        	}
        	if (sum/10 > 0) {
        		a = 1;
        	} else {
        		a = 0;
        	}
        	sum = sum%10;
        	ListNode tmp = new ListNode(sum);
        	if (res == null) {
        		head = tmp;
        	} else {
        		res.next = tmp;
        	}
        	res = tmp;
        }
        if (a == 1) {
        	ListNode tmp = new ListNode(1);
        	res.next = tmp;
        }
        return head;
    }
}

 

你可能感兴趣的:(LeetCode)