leetcode第二题java_Leetcode第二题解题java实现

问题:

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值