Lintcode-easy-add numbers

Source: Internet
Author: User

You have both numbers represented by a linked list, where each node contains a single digit. reversethe digits is stored in order, such the 1 's digit is at the head of the list. Write a function that adds the numbers and returns the sum as a linked list.

Example

Given 7->1->6 + 5->9->2 . That's, 617 + 295 .

Return 2->1->9 . That's 912 .

Given 3->1->5 5->9->2 and, return 8->0->8 .

There's not much to say about this question, and it's about the same as putting two binary numbers together.

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int       X) {* val = x; * next = NULL; *     } * } */ Public classSolution {/**     * @paraml1:the First list *@paraml2:the Second list *@return: The sum list of L1 and L2*/     PublicListNode addlists (listnode L1, ListNode L2) {//Write your code here                if(L1 = =NULL)            returnL2; if(L2 = =NULL)            returnL1; ListNode Fakehead=NewListNode (0); ListNode P=Fakehead; ListNode P1=L1; ListNode P2=L2; intCarry = 0;  while(P1! =NULL|| P2! =NULL){            intNUM1 = 0; intnum2 = 0; if(P1! =NULL) {NUM1=P1.val; P1=P1.next; }            if(P2! =NULL) {num2=P2.val; P2=P2.next; } P.next=NewListNode ((NUM1 + num2 + carry)% 10); P=P.next; Carry= (NUM1 + num2 + carry)/10; }                if(Carry = = 1) {P.next=NewListNode (1); P=P.next; }                returnFakehead.next; }}

Lintcode-easy-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.