码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]2. 两数相加

时间:2020-09-17 19:08:34      阅读:21      评论:0      收藏:0      [点我收藏+]

标签:一个   numbers   相加   init   sum   官方   nod   处理   solution   

2. 两数相加

这题medium,但思路挺简单的。模拟下就可以

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *rst = new ListNode(0);
        ListNode *head = rst;
        int tmp = 0;
        while(l1 && l2) {
            int sum = l1->val + l2->val + tmp;
            rst->next = new ListNode(sum%10);
            tmp = sum/10;
            rst = rst->next;
            l1 = l1->next;l2 = l2->next;
        }
        while(l1) {
            int sum = l1->val + tmp;
            rst->next = new ListNode(sum%10);
            tmp = sum/10;
            rst = rst->next;
            l1 = l1->next;
        }
        while(l2) {
            int sum = l2->val + tmp;
            rst->next = new ListNode(sum%10);
            tmp = sum/10;
            rst = rst->next;
            l2 = l2->next;
        }
        if(tmp>0) {
            rst->next = new ListNode(1);
        }
        return head->next;
    }
};

对比下官方解答,把l1,l2短的那个“补齐”了处理,可以在一个while里面写完。思路是一样的

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]2. 两数相加

标签:一个   numbers   相加   init   sum   官方   nod   处理   solution   

原文地址:https://www.cnblogs.com/pusidun/p/13636332.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!