[leetcode练习记录]两数相加

题目描述:

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

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

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

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

个人解答:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       		ListNode head = new ListNode(0);
		ListNode node = head;
		int sum = 0;
		
		while(true) {
			node.next = new ListNode((l1.val + l2.val + sum) % 10);
			node = node.next;
			sum = (l1.val + l2.val + sum) /10 ;
			if (l1.next == null) {
				l1.val = 0;
				if (l2.next == null) {
					if(sum != 0) {
						node.next = new ListNode(sum);
					}
					break;
				}
				l2 = l2.next;
			} else {
				l1 = l1.next;
				if (l2.next == null) {
					l2.val = 0;
				} else {
					l2 = l2.next;
				}
			}
		}
		
		return head.next;
    }
}

 

官方题解:

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;
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-xiang-jia-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

总结:

个人在最开始做的时候考虑先用int或者long去存储计算的汇总值,但是没有考虑这两种类型的精度限制,实属惭愧。

同时在解题过程中又好几次因为循环的时候忘记next,导致出现死循环而超时,这些小细节后续都需要注意。

总体解题思路和官方相差不大,主要是以上细节后续需要多注意。

1. 精度

2. 死循环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值