[Leetcode] add two numbers

Source: Internet
Author: User

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

There are multiple solutions to this question:

(1) convert two linked lists into numbers, calculate the numbers, and then convert them into linked lists:

I think this is also an idea. Although it is difficult to calculate, it is easy to think about.

However, note: integer operations may easily go beyond the range, leading to returned error results. So we can accept numbers with double or float. However, you must use while (Num> = 1) to determine whether the number of num has been obtained. Because the integers are automatically rounded up, float and double must be manually processed.

In terms of time complexity, it takes a little time than (2), but it is also O (n) time.

(2) From the two linked list headers to the end, a carry constant is used to represent carry. Since it is in reverse order, we just need to traverse it directly.

But one thing to note is that the question does not mean that the two linked lists are of the same length. Then, we just like mergesort, add the extra section and carry it for computation.

Finally, you have to judge: If carry is equal to 1, it means that the new number is one more than the previous one. Such as 99999 + 1. In this case, add a 1-node instance.

There are a lot of code duplicates. We should be able to optimize the latter two while and integrate them together. But there is no problem with the idea.

O (n) Time leetcode passed once.


public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {if (l1 == null && l2 == null)return null;double num1 = ListToNumber(l1);double num2 = ListToNumber(l2);return NumberToList(num1 + num2);}public static ListNode NumberToList(double num) {ListNode head = new ListNode(0);ListNode res = head;if (num < 10)return new ListNode((int) num);while (num >= 1) {int lastdigit = (int) (num % 10);num = num / 10;head.next = new ListNode(lastdigit);head = head.next;}return res.next;}public static double ListToNumber(ListNode head) {if (head == null)return 0;double num = 0;double base = 1;while (head != null) {num += head.val * base;head = head.next;base = base * 10;}return num;}


Solution 2 (recommended)

     public  ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1==null && l2==null) return null;        ListNode res=new ListNode(1);        ListNode dummy=res;        int carry=0;        while(l1!=null && l2!=null){            int val=l1.val+l2.val+carry;            if(val>9){                val=val%10;                carry=1;            } else {                carry=0;            }            res.next=new ListNode(val);            res=res.next;            l1=l1.next;            l2=l2.next;        }                while(l1!=null){            int val=l1.val+carry;            if(val>9){                val=val%10;                carry=1;            } else {                carry=0;            }            res.next=new ListNode(val);            res=res.next;            l1=l1.next;        }                while(l2!=null){            int val=l2.val+carry;            if(val>9){                val=val%10;                carry=1;            } else {                carry=0;            }            res.next=new ListNode(val);            res=res.next;            l2=l2.next;        }                if(carry==1){            res.next=new ListNode(1);        }                return dummy.next;            }



[Leetcode] add two 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.