LeetCode 2.Add Two Numbers

题目:

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

思路:

题目内容为以链表输出两个链表反向相加的结果,一开始的思路是先将两个链表恢复成反向存储的整数,将两数求和后,再取反存在链表中,循环较多,计算量大,同时提交不成功,后发现可以从两个链表的开头依次两两相加,如果和大于9,向右侧进一位。

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
       //正着加反着加一样
       //curr用于存放当前结果 
        ListNode l3 = new ListNode(0);
        ListNode curr = l3,p = l1,q = l2;
        int x = 0,y = 0,i = 0,sum = 0;
        while( p != null ||  q != null){
            x = (p != null) ? p.val : 0;
            y = (q != null) ? q.val : 0;
            sum = x + y + sum;
            curr.next = new ListNode(sum%10);
            curr=curr.next;
            sum = sum / 10;
            if(p != null) p = p.next;
            if(q != null) q = q.next;
        }
        //当最后一位两两相加的和大于9时,向最右侧再进一位
        if(sum != 0){
            curr.next = new ListNode(sum);
        }
        return l3.next;
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值