码疯窝

LeetCode 每日一题 — Add Two Numbers

2014/12/31 11:37:40    分类: 日志连载    0人评论 次浏览

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

算法分析: 两个ListNode 相加, 向右进位

Java:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode rst = new ListNode(0);
        ListNode tmp1 = l1;
        ListNode tmp2 = l2;
        ListNode tmprst = rst;
        int carry = 0;
        int v = 0;
        while(tmp1 != null || tmp2 != null) {
            v = (tmp1 == null ? 0 : tmp1.val) + (tmp2 == null ? 0 : tmp2.val) + carry;
            carry = 0;
            if (v > 9) {
                carry = v / 10;
                v %= 10;
            }
            tmprst.next = new ListNode(v);
            tmprst = tmprst.next;
            tmp1 = tmp1 == null ? null : tmp1.next;
            tmp2 = tmp2 == null ? null : tmp2.next;
        }
        if (carry > 0) {
            tmprst.next = new ListNode(carry);
        }
        return rst.next;
    }
}

C++:

 

Python:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
        if (l1 == None):
            return l2
        elif (l2 == None):
            return l1
        
        rst = ListNode(0)
        tmprst = rst
        tmp1 = l1
        tmp2 = l2
        carry = 0
        v = 0
        while(tmp1 != None or tmp2 != None):
            v = (tmp1.val if tmp1 != None else 0) + (tmp2.val if tmp2 != None else 0) + carry
            carry = 0
            if (v > 9):
                carry = v / 10
                v %= 10
            tmprst.next = ListNode(v)
            tmprst = tmprst.next
            tmp1 = tmp1.next if tmp1 != None else None
            tmp2 = tmp2.next if tmp2 != None else None
        
        if (carry > 0):
            tmprst.next = ListNode(carry)
        return rst.next
            
                
        
继续查看有关 日志连载的文章

0个访客评论