当前位置:网站首页>2. add two numbers

2. add two numbers

2022-06-22 00:58:00 HMTT

2. Addition of two numbers

Here are two for you Non empty The linked list of , Represents two nonnegative integers . Each of them is based on The reverse Stored in , And each node can only store a Numbers .

Please add up the two numbers , And returns a linked list representing sum in the same form .

You can assume that in addition to the numbers 0 outside , Neither of these numbers 0 start .

Example 1:

img

 Input :l1 = [2,4,3], l2 = [5,6,4]
 Output :[7,0,8]
 explain :342 + 465 = 807.

Example 2:

 Input :l1 = [0], l2 = [0]
 Output :[0]

Example 3:

 Input :l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
 Output :[8,9,9,9,0,0,0,1]

Tips :

  • The number of nodes in each list is in the range [1, 100] Inside
  • 0 <= Node.val <= 9
  • The title data guarantees that the number indicated in the list does not contain leading zeros

Code

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
    
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    
        //  Return the header pointer of the result 
        ListNode result = new ListNode();

        //  The tail node used to store the results 
        ListNode p = result;

        //  Indicates whether there is carry  1: Yes , 0: No, 
        int flag = 0;

        //  Variables used to store intermediate values of operations 
        int num1 = 0;
        int num2 = 0;
        int tmp = 0;
        /** * l1 != null || l2 != null  Hold until both lists are traversed  * flag != 0  True means no carry  * *  When both lists are traversed , And when there is no carry , The loop ends  */
        while(l1 != null || l2 != null || flag != 0) {
    
            /** * [1],[1,1,1] *  Can be seen as  * [1,0,0],[1,1,1] *  When one of the lists is traversed , All the numbers are in 0 replace  */
            num1 = (l1 == null) ? 0 : l1.val;
            num2 = (l2 == null) ? 0 : l2.val;

            /** *  Calculate the corresponding sum , *  If exceeded 10, carry (flag = 1) *  If it is less than 10,  No carry (flag = 0) *  And then put   Sum of two numbers   Add single digits to the result list  */
            tmp = num1 + num2 + flag;
            flag = tmp / 10;
            tmp = tmp % 10;
            p.next = new ListNode(tmp);
            p = p.next;

            /** *  Only when the list is not empty , To move the pointer  *  Prevent a blank scene  */
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }

        //  Returns the list after the header pointer 
        return result.next;
    }
}
原网站

版权声明
本文为[HMTT]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206212347164774.html