`
hcx2013
  • 浏览: 83388 次
社区版块
存档分类
最新评论

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;
    }
}

 

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    var head, res, a = 0;
    while (l1 || l2) {
    	var sum = a;
    	if (l1) {
    		sum += l1.val
    		l1 = l1.next;
    	}
    	if (l2) {
    		sum += l2.val
    		l2 = l2.next;
    	}
    	if (sum >= 10) {
    		a = 1;
    	} else {
    		a = 0;
    	}
    	sum = sum % 10;
    	var tmp = new ListNode(sum);
    	if (res === undefined) {
    		head = tmp;
    	} else {
    		res.next = tmp;
    	}
    	res = tmp;
    }
    if (a === 1) {
    	tmp = new ListNode(a);
    	res.next = tmp;
    }
    return head;
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics