Leetcode第二题解题java实现

来源:互联网 发布:图片制作软件app 编辑:程序博客网 时间:2024/05/16 23:52

问题:

You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

审题:

该题把数字按位拆开以倒序方式存放在一个链表中,要求计算两个数字的和,以同样的方式返回。该题的考察点是链表的遍历,他以倒序存储数字,减低了解题的繁琐程度,想象一下,分别从两个链表中同时取出一个数,比如第一个,这两数都是个位上的数,直接相加即可,得到的数看是否有进位,把进位值记下。
我的想法是把两个链表的数挨个遍历取出,没取出一位数就相加再加进位,并对10求余,存到另外一个链表的节点中,取整得到进位,存起来,
一直循环到两链表为空。

解题:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        if(l1 == null && l2 == null)        {            return null;        }        ListNode lhead;        ListNode l = new ListNode(0);        lhead = l;        int flag=0;        while(l1!=null || l2!=null)        {            ListNode lnext = new ListNode(0);            int a = l1==null?0:l1.val;            int b = l2==null?0:l2.val;            lnext.val = (a+b+flag)%10;            flag = (a+b+flag)/10;            l.next = lnext;            l = l.next;            l1 = l1==null?null:l1.next;            l2 = l2==null?null:l2.next;        }        if(flag != 0)    //如果还有进位,添加节点存入其中        {            ListNode lnext = new ListNode(0);            lnext.val = flag;            l.next = lnext;        }        return lhead.next;    }}

该解题思维相对正常,是靠生活计算经验解题,没有复杂算法,排名居中。

0 0
原创粉丝点击