2 Add Two Numbers LeeCode

Posted 洽洽老大

tags:

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

Question: 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

给定两个逆序列表,返回两个相加的结果,注意处理进位

public class Solution 

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) 
       ListNode result = new ListNode(0);
       ListNode tt = result;
       int up = 0;//进位

       while(l1!=null || l2!=null)
           int m =0,n = 0;
           if(l1!=null) m = l1.val;l1 = l1.next;
           if(l2!=null) n = l2.val;l2 = l2.next;
           int a = m+n+up;
           tt.next = new ListNode(a%10);
           tt = tt.next;
           up = a/10;

       
       if(up ==1)
           tt.next = new ListNode(1);
       
       return result.next;

    

以上是关于2 Add Two Numbers LeeCode的主要内容,如果未能解决你的问题,请参考以下文章

2. Add Two Numbers

Leetcode 2. Add Two Numbers

Leetcode 2. Add Two Numbers

2. Add Two Numbers

2. Add Two Numbers

2. Add Two Numbers