• 0002. Add two numbers (M)


    Add two numbers (M)

    题目

    You are given two non-empty linked lists representing two non-negative integers. 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.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Example:

    Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 0 -> 8
    Explanation: 342 + 465 = 807.
    

    题意

    以各位数倒序排列链表的形式给定两个整数,要求计算出两者之和,并同样以各位数倒序链表的形式返回结果。

    思路

    从两链表的个位数开始,依次计算各位数之和并判断记录进位。最后注意对最高位的进位进行处理。(注意先转换为两个整数再相加的方法会存在超过上限的问题)


    代码实现

    Java

    class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);        // 创建头结点便于输出结果
            ListNode cur = head;
            int carry = 0;
            int a = 0, b = 0, c = 0;
            
            while (l1 != null || l2 != null) {
                a = (l1 == null)? 0 : l1.val;
                b = (l2 == null)? 0 : l2.val;
                c = a + b + carry;              
                carry = c / 10;             // 判断进位
                c = c % 10;
                cur.next = new ListNode(c);
                cur = cur.next;
                l1 = (l1 == null)? null : l1.next;
                l2 = (l2 == null)? null : l2.next;
            }
            // 最高位进位情况处理
            if (carry != 0) {
                cur.next = new ListNode(carry);
            }
            
            return head.next;
        }
    }
    

    JavaScript

    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} l1
     * @param {ListNode} l2
     * @return {ListNode}
     */
    var addTwoNumbers = function (l1, l2) {
      let head = new ListNode()
      let p = head
      let carry = 0
      while (l1 !== null || l2 !== null) {
        let sum = carry
        sum += l1 === null ? 0 : l1.val
        sum += l2 === null ? 0 : l2.val
        p.next = new ListNode(sum % 10)
        carry = Math.floor(sum / 10)
        p = p.next
        if (l1 !== null) l1 = l1.next
        if (l2 !== null) l2 = l2.next
      }
      if (carry !== 0) {
        p.next = new ListNode(carry)
      }
      return head.next
    }
    
  • 相关阅读:
    WebClient与WebRequest差异
    自定义控件的构建(4)
    自定义控件的构建(6)
    Sliverlight中PagedCollectionView的总结
    自定义控件的构建(13)
    自定义控件的构建(8)
    Silverlight中的主题设置
    自定义控件的构建(12)
    自定义控件的构建(7)
    谈谈学完Asp.net 中的自定义控件后的感受
  • 原文地址:https://www.cnblogs.com/mapoos/p/13130225.html
Copyright © 2020-2023  润新知