每日leetcode-Add Two Numbers

3,624次阅读
没有评论

共计 879 个字符,预计需要花费 3 分钟才能阅读完成。

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

 

感觉这个题目的理解有点问题啊!上述红字的部分难道不是说链表的每个节点的存储顺序是逆序的,然后实际上就是逆序相加并且记录进位?

自己实际测试的时候仍然得到的结果是顺序的。。。。

实现代码

 

/**
 * 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* p = new ListNode(0);
        ListNode* head=p;
        int cn = 0;

        while(l1 || l2) {
            int val = cn + (l1 ? l1->val : 0) + (l2 ? l2->val : 0);
            cn = val / 10;
            val = val % 10;
            p->next = new ListNode(val);
            p = p->next;
            if(l1) {
                l1 = l1->next;
            }
            if(l2) {
                l2 = l2->next;
            }
        }

        if(cn != 0) {
            p->next = new ListNode(cn);
            p = p->next;
        }

        return head->next;  
        
    }
};
此部分实验数据是自定义的,是为了验证题目中的红字部分,这特么不是顺序相加?
Run Code Result:
Your input
[1,5,6]
[3,2,5]
Your answer
[4,7,1,1]
Expected answer
[4,7,1,1]
Runtime: 1 ms
正文完
请博主喝杯咖啡吧!
post-qrcode
 
admin
版权声明:本站原创文章,由 admin 2016-04-03发表,共计879字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码