[LeetCode][JavaScript]Add Two Numbers

來源:互聯網
上載者:User

標籤:

Add Two Numbers

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

https://leetcode.com/problems/add-two-numbers/

 

 

 

 

 

 

鏈表儲存的大數加法。

 1 /** 2  * Definition for singly-linked list. 3  * function ListNode(val) { 4  *     this.val = val; 5  *     this.next = null; 6  * } 7  */ 8 /** 9  * @param {ListNode} l110  * @param {ListNode} l211  * @return {ListNode}12  */13 var addTwoNumbers = function(l1, l2) {14     var carry = 0;15     var result = new ListNode(-1);16     var resHead = result;17     while(l1 !== null || l2 !== null){18         var sum = carry;19         if(l1 !== null){20             sum += l1.val;21             l1 = l1.next;22         }23         if(l2 !== null){24             sum += l2.val;25             l2 = l2.next;26         }27 28         var node = null;29         if(sum >= 10){30             node = new ListNode(sum - 10);31             carry = 1;32         }else{33             node = new ListNode(sum);34             carry = 0;35         }36         result.next = node;37         result = result.next;38     }39     if(carry === 1){40         result.next = new ListNode(1);41     }42     return resHead.next;43 };

 

 

 

 

[LeetCode][JavaScript]Add Two Numbers

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.