java 2.添加两个Numbers.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 2.添加两个Numbers.java相关的知识,希望对你有一定的参考价值。

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

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
"""

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

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if not l1 and not l2:
            return [];
        
        temp = ListNode(0);
        res = temp;
        # use res to store the head pointer of result's linked list. 
        # The result starts from res.next
        
        flag = 0;
        
        while(l1 or l2):
            a = 0; 
            b = 0;
            if l1:
                a = l1.val;
                l1 = l1.next;
            if l2:
                b = l2.val;
                l2 = l2.next;
            s = a + b + flag;
            flag = s / 10;
            temp.next = ListNode(s%10);
            temp = temp.next;
            
            
            
        if flag == 1:
            temp.next = ListNode(1);
        
        return res.next;
                
/**
 * 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 res = new ListNode(-1);
        ListNode temp = res;
        int carry = 0;
        while (l1 != null || l2 != null) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            temp.next = new ListNode(carry % 10);
            temp = temp.next;
            carry /= 10;
        }
        if (carry > 0) temp.next = new ListNode(carry);
        return res.next;
    }
}

以上是关于java 2.添加两个Numbers.java的主要内容,如果未能解决你的问题,请参考以下文章

java 2.添加两个Numbers.java

java 2.添加两个Numbers.java

java 2.添加两个Numbers.java

java 2.添加两个Numbers.java

Leetcode 2. Add Two Numbers (java)

leetcode 2. Add Two Numbers [java]