美文网首页
2. 两数相加

2. 两数相加

作者: HITZGD | 来源:发表于2018-09-19 17:01 被阅读0次
/**
 * 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) {
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        if (l1 == NULL && l2 == NULL) return NULL;
        ListNode* dummyHead = new ListNode(0);
        ListNode* p = l1, *q = l2;
        ListNode* current = 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;
            current->next = new ListNode(sum % 10);
            current = current->next;
            if (p != NULL) p = p->next;
            if (q != NULL) q = q->next;
        }
        if (carry > 0 )
        {
            current->next = new ListNode(carry);
        }
        return  dummyHead->next;
        
    }
};

相关文章

  • 2. 两数相加

    给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表...

  • 2. 两数相加

  • 2. 两数相加

    一、题目原型: 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加...

  • 2. 两数相加

    题目 解析 本题只需要遍历一下单链表,将单链表的值添加到StringBuilder对象后然后转化成数字进行运算再反...

  • 2.两数相加

    题目 思路1.记录返回结构体2.两个结构体的两位数相加,记录进位3.位移结构体,赋值代码

  • 2. 两数相加

    https://leetcode-cn.com/problems/add-two-numbers/descript...

  • 2. 两数相加

    补充:我们现在的这种第一个节点是头节点。所以要 root.next如果我的 不想用这种方式 会遇到这样的问题。

  • 2. 两数相加

    链接:https://leetcode-cn.com/problems/add-two-numbers/ 代码地址...

  • 2.两数相加

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

  • 2. 两数相加

    题目 分析 解题方案: 初等数学 我们使用变量来跟踪进位,并从包含最低有效位的表头开始模拟逐位相加的过程。 就像你...

网友评论

      本文标题:2. 两数相加

      本文链接:https://www.haomeiwen.com/subject/bsginftx.html