Add Two Numbers II问题及解法

来源:互联网 发布:武汉火凤凰云计算基地 编辑:程序博客网 时间:2024/05/18 20:52

问题描述:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

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

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

示例:

Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7

问题分析:

两数相加问题,注意考虑溢出问题,这里采用字符串的加减法。


过程详见代码:

/** * 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) {        string res1, res2;while (l1){res1.push_back(l1->val + '0');l1 = l1->next;}while (l2){res2.push_back(l2->val + '0');l2 = l2->next;}int flag = 0,t;int i = res1.size() - 1,j = res2.size()- 1;ListNode * curNode, *head = nullptr;while (i >= 0 || j >= 0){if (i >= 0 && j >= 0){t = res1[i] - '0' + res2[j] - '0' + flag;i--;j--;}else if (i >= 0){t = res1[i] - '0' + flag;i--;}else{t = res2[j] - '0' + flag;j--;}flag = t / 10;curNode = new ListNode(t % 10);curNode->next = head;head = curNode;}        if (flag){curNode = new ListNode(flag);curNode->next = head;head = curNode;}return head;    }};


原创粉丝点击