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; }};
阅读全文
0 0
- Add Two Numbers II问题及解法
- Add Two Numbers问题及解法
- Add Two Numbers 解法
- Add Two Numbers II
- Add Two Numbers II
- Add Two Numbers II
- Add Two Numbers II
- 445. Add Two Numbers II
- [LeetCode]Add Two Numbers II
- Add Two Numbers II ---LeetCode
- 445. Add Two Numbers II
- LeetCode445. Add Two Numbers II
- 445. Add Two Numbers II
- Leetcode Add Two Numbers II
- 445. Add Two Numbers II**
- 445. Add Two Numbers II
- leetcode_middle_12_445. Add Two Numbers II
- 445. Add Two Numbers II
- 【POJ】3180
- 排序之交换排序:冒泡排序and快速排序
- 二进制到八进制的转换
- AVFoundation学习笔记(二):视频播放相关
- absolute和relative总结
- Add Two Numbers II问题及解法
- HDU 6085 Rikka with Candies(bitset操作+思路转化)
- make[2]: *** No rule to make target '/usr/lib/x86_64-linux-gnu/libGL.so'
- redis安装及注意事项
- 01背包,完全背包模板
- Burp Intruder使用
- Gentoo添加用户并配置sudo权限
- AI数学基础(2)——数学期望、方差和最小二乘法
- Zookeeper的介绍