美文网首页
LeetCode - Add Two Numbers - Jav

LeetCode - Add Two Numbers - Jav

作者: 音符纸飞机 | 来源:发表于2018-10-11 14:24 被阅读3次

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 contains 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.

Java

/**
 * 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(-1);
        ListNode ret = dummy;
        int sum = 0;
        while (l1 != null || l2 != null){
            if (l1!=null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2!=null) {
                sum += l2.val;
                l2 = l2.next;
            }
            dummy.next = new ListNode(sum%10);
            dummy = dummy.next;
            sum = sum/10;
        }
        if (sum != 0){
            dummy.next = new ListNode(sum);
        }

        return ret.next;
    }
}

Python

divmod(a,b) 返回 a÷b 的商和余数

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

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy = ListNode(-1)
        ret = dummy
        sum = 0
        while l1 or l2:
            if l1:
                sum += l1.val
                l1 = l1.next
            if l2:
                sum += l2.val
                l2 = l2.next
            sum, val = divmod(sum, 10)
            dummy.next = ListNode(val)
            dummy = dummy.next
        if sum > 0:
            dummy.next = ListNode(sum)
        return ret.next
            
        

相关文章

网友评论

      本文标题:LeetCode - Add Two Numbers - Jav

      本文链接:https://www.haomeiwen.com/subject/eksbaftx.html