美文网首页
2018-09-17 342 + 465 = 807.

2018-09-17 342 + 465 = 807.

作者: 最美下雨天 | 来源:发表于2018-09-17 19:13 被阅读18次

题目来源:https://github.com/Blankj/awesome-java-leetcode/blob/master/note/002/README.md
是github上的一位作者分享的

解题思路:342+465=807


/**
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
 * Output: 7 -> 0 -> 8
 * Explanation: 342 + 465 = 807.
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class First {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //最终要输出的链表
        ListNode node = new ListNode(0);

        ListNode n1 = l1, n2 = l2, t = node;
        int sum = 0;
        while (n1 != null || n2 != null) {
            //巧妙之处
            sum /= 10;
            if (n1 != null) {
                sum += n1.val;
                n1 = n1.next;
            }
            if (n2 != null) {
                sum += n2.val;
                n2 = n2.next;
            }
            //巧妙之处
            t.next = new ListNode(sum % 10);
            t = t.next;
        }
        //巧妙之处
        if (sum / 10 != 0) t.next = new ListNode(1);
        return node.next;
    }

    public static  void main(String[] args)
    {
        First first=new First();
        ListNode input1=new ListNode(2);
        ListNode input2=new ListNode(4);
        input1.next=input2;
        ListNode input3=new ListNode(3);
        input2.next=input3;

        ListNode input11=new ListNode(5);
        ListNode input12=new ListNode(6);
        input11.next=input12;
        ListNode input13=new ListNode(4);
        input12.next=input13;

        ListNode sum=first.addTwoNumbers(input1,input11);

        while (sum!=null)
        {
            System.out.println(sum.val);
            sum=sum.next;
        }


    }
}

class ListNode{
    int val;
    ListNode next;
    ListNode(int x)
    {
        val=x;
    }
}

输出:


image.png

相关文章

  • 2018-09-17 342 + 465 = 807.

    题目来源:https://github.com/Blankj/awesome-java-leetcode/blob...

  • ARTS 第6周

    [TOC] Algorithm 807. Max Increase to Keep City Skyline 难度...

  • [python] 2019-03-06

    .807. Max Increase to Keep City Skyline note: map()函数lr =...

  • 素言

    2018-09-17

  • 2018-09-18

    2018-09-17 戚洋洋 2018-09-17 21:13 · 字数 468 · 阅读 9 · 日记本 敬爱的...

  • 时间组件

    /** @Author:YE @Update:2018-09-17 @param:format ,onInputC...

  • 7天6晚,邂逅马来西亚的悠闲

    出发时间/2018-09-17 出行天数/7 天 人物/和朋友 ...

  • 【Google Arts & Culture】2018-09-2

    2018-09-22 Saturday source 2018-09-17 Monday source 2018-...

  • 465

    原画有种清纯又妩媚的矛盾美,我画的有点糟心。

  • 465

    第二个休息,五四青年节,温度刚刚好,早上爸妈出去溜达,买了点吃的就回来了,说太冷了,中午吃的馅饼,晚上要吃面条,吃...

网友评论

      本文标题:2018-09-17 342 + 465 = 807.

      本文链接:https://www.haomeiwen.com/subject/rpfdnftx.html