Leetcode 2---Add binary Numbers carry list Math

Source: Internet
Author: User

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: You can refer to the binary number add the problem, but this topic is different from left to right, that is, carry the right to move (enough wonderful), so simple, direct shift on the line, you need to pay attention to the structure of the list and the null pointer. With the help of dummy nodes and double pointers, it is easy to solve the problem, one is responsible for the shift, and one is responsible for storage.

/**
 * 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 pre= New ListNode (0);
     ListNode Head=pre;
     int carry=0;
     while (l1!=null| | l2!=null| | carry!=0) {
            listnode curr=new listnode (0);
            int sum= (l1==null?0:l1.val) + (l2==null?0:l2.val) +carry;
            CARRY=SUM/10;
            curr.val=sum%10;
            pre.next=curr;//equivalent to storage, assignment
            pre=curr;//shift
            l1= (l1==null?null:l1.next);
            L2= (L2==null?null:l2.next);
        }
        return head.next;
    }
}

If the title changes, the carry is from right to left, this time you have to consider the reverse of the list ....

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.