• 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
    }
    
  • 相关阅读:
    自定义排序方式
    Ajax 调用(传值)一般处理程序(.ashx)
    把一个文件夹下的所有excel添加到datatable
    list比较交集
    禁用未登录通过连接下载文件
    加密方式
    使用response.write输出excel
    linux安装OpenCV以及windows安装numpy、cv2等python2.7模块
    哈希长度扩展攻击(Hash Length Extension Attack)利用工具hexpand安装使用方法
    yafu安装使用方法以及mismatched parens解决方法
  • 原文地址:https://www.cnblogs.com/mapoos/p/13130225.html
Copyright © 2020-2023  润新知