简单算法题:leetcode-2 两数相加

算法撸一遍,从简单的开始。算法

作leetcode题目的时候,常常百度答案,但感受大多不是我想要的,不少我不能理解。如今也作了一些算法题,哪些并非很深奥,但须要一些技巧,简单的算法题更多的是经验值。这里,开启算法题篇章。给本身记忆,但愿不要误人子弟。bash

题目

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,而且它们的每一个节点只能存储 一位 数字。ui

若是,咱们将这两个数相加起来,则会返回一个新的链表来表示它们的和。spa

您能够假设除了数字 0 以外,这两个数都不会以 0 开头。code

示例:leetcode

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
缘由:342 + 465 = 807复制代码

解题

看完题目,简单点理解就是 1+1=2的题目。只不过是用链表存的数据class

思路

1:循环链表,取出全部数据,两个链表都为空为止百度

2:同位数相加,大于10要取余进一List

代码

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode listNode = new ListNode(0);//用来存储
    ListNode listNode2 = listNode;
    int z = 0 ;
    while (l1 != null && l2 != null){
        int x ;
        int y ;
        x = l1 != null ? l1.val : 0; //若是为空的话 用0赋值
        y = l2 != null ? l2.val : 0;
        listNode2.next = new ListNode((x + y + z) % 10);//计算取余
        listNode2 = listNode2.next;
        z = (x + y + z) >= 10 ?1:0;
        if (l1 != null)l1 = l1.next ; //下一位
        if (l2 != null)l2 = l2.next ;
    }
    if (z > 0 ){
        listNode2.next = new ListNode(z);
    }
    return listNode.next ;
}复制代码

其余代码循环

public static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
}复制代码

public static void main(String[] age){
    ListNode listNode1 = new ListNode(2);
    ListNode listNode2 = new ListNode(4);
    ListNode listNode3 = new ListNode(3);
    listNode2.next = listNode3;
    listNode1.next = listNode2;


    ListNode listNode4 = new ListNode(5);
    ListNode listNode5 = new ListNode(6);
    ListNode listNode6 = new ListNode(4);
    listNode5.next = listNode6;
    listNode4.next = listNode5;


    ListNode listNode = addTwoNumbers(listNode1, listNode4);
    while (listNode != null){
        System.out.println(listNode.val);
        listNode = listNode.next;
    }
}复制代码
相关文章
相关标签/搜索