• 链表相加(Add Two Numbers)


    描述:

    给定两个非空的链表,表示两个非负整数。数字以相反的顺序存储,每个节点包含一个数字。添加两个数字并将其作为链表返回。

    您可以假设两个数字不包含任何前导零,除了数字0本身。

    输入:(2 - > 4 - > 3)+(5 - > 6 - > 4)
    输出: 7 - > 0 - > 8

    类似于:342+564 = 807

    LeetCode解决方案:

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1, q = l2, curr = dummyHead;
        int carry = 0;
        while (p != null || q != null) {
            int x = (p != null) ? p.val : 0;
            int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            carry = sum / 10;
            curr.next = new ListNode(sum % 10);
            curr = curr.next;
            if (p != null) p = p.next;
            if (q != null) q = q.next;
        }
        if (carry > 0) {
            curr.next = new ListNode(carry);
        }
        return dummyHead.next;
    }

     我的方法:

    class Solution {
            public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
                ListNode dummyHead = new ListNode(0);
                ListNode p = l1, q = l2, curr = dummyHead;
                int carry = 0;
                while (true) {
                    //做相加
                    int x = (p != null) ? p.val : 0;
                    int y = (q != null) ? q.val : 0;
                    int sum = carry + x + y;
                    curr.val = sum % 10;
                    //重新赋值carry、p、q和curr
                    carry = sum / 10;
                    
                    if (p != null) p = p.next;
                    if (q != null) q = q.next;
                    if(p == null && q == null) break;
                   
                    curr.next = new ListNode(0);
                    curr = curr.next;
                   
                    }
                if (carry > 0) {
                    curr.next = new ListNode(carry);
                    }
                return dummyHead;
            }
        }
  • 相关阅读:
    A Bayesian Approach to Deep Neural Network Adaptation with Applications to Robust Automatic Speech Recognition
    nnet3的代码分析
    Kaldi中的L2正则化
    HMM拓扑与转移模型
    Kaldi阅读并更改代码
    nnet3中的数据类型
    nnet3配置中的“编译”
    Kaldi的delta特征
    Kaldi的交叉熵正则化
    【搜索】 Prime Path
  • 原文地址:https://www.cnblogs.com/K-artorias/p/7654540.html
Copyright © 2020-2023  润新知