Java [Leetcode 2] Add Numbers

Source: Internet
Author: User
Tags add numbers

Problem Description:

You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.

Input: (2, 4, 3) + (5, 6, 4)
Output: 7, 0, 8

Problem Solving Ideas:

Set up a head listnode and tail listnode, two lists start from the beginning, 22 add and set the carry carry, if the sum of more than 10 carry 1, otherwise zero. At the same time, consider a list and the length, the other end of the situation.

The code is as follows:

1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9  *     }Ten  * } One  */ A  Public classSolution { -      PublicListNode addtwonumbers (listnode L1, ListNode L2) { -          theListNode head =NewListNode (0); -ListNode tail =head; -           intsum = 0; -           intCarry = 0; +            -            while(L1! =NULL|| L2! =NULL){ +               if(L1 = =NULL){ Asum = L2.val +carry; atL2 =L2.next; -               } -               Else if(L2 = =NULL){ -sum = L1.val +carry; -L1 =L1.next; -               } in               Else{ -sum = l1.val + L2.val +carry; toL1 =L1.next; +L2 =L2.next; -               } the                *               if(Sum >= 10){ $carry = SUM/10;Panax Notoginsengsum = sum% 10; -               } the               Else{ +Carry = 0; A               } the                +Tail.next =Newlistnode (sum); -Tail =Tail.next; $           } $            -           if(Carry! = 0){ -Tail.next =NewListNode (carry); theTail =Tail.next; -           }Wuyi            the           returnHead.next; -     } Wu}

Java [Leetcode 2] Add Numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.