zoukankan      html  css  js  c++  java
  • [LeetCode][JavaScript]Add Two Numbers

    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} l1
    10  * @param {ListNode} l2
    11  * @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 };
  • 相关阅读:
    01-Django 简介
    函数及函数的嵌套等
    循环及循环嵌套
    运算符
    if, elif, else及if嵌套
    变量及变量计算和引用
    Python的3种执行方式
    Jmeter设置默认中文启动
    Vysor
    python基础学习(二)
  • 原文地址:https://www.cnblogs.com/Liok3187/p/4592057.html
Copyright © 2011-2022 走看看