leetcode - Add Two Numbers
2014-09-05 10:24
309 查看
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
题目意思很简单,有点类似两个链表归并
个人思路:
1,同时从头结点开始遍历两个链表,将对应的两个结点以及进位相加,和记为temp,进位记为flag,temp % 10是结果链表对应结点的值,temp / 10是进位flag
2,不断循环,直到某个链表遍历完,然后将未遍历完链表的剩余部分与进位相加,处理方式同1,直到该链表也遍历完
3,注意一下最后的进位flag是否为1,为1则表示最后结点的和是有进位的,需要再向高位进1
代码:
View Code
网上基本是这个思路
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
题目意思很简单,有点类似两个链表归并
个人思路:
1,同时从头结点开始遍历两个链表,将对应的两个结点以及进位相加,和记为temp,进位记为flag,temp % 10是结果链表对应结点的值,temp / 10是进位flag
2,不断循环,直到某个链表遍历完,然后将未遍历完链表的剩余部分与进位相加,处理方式同1,直到该链表也遍历完
3,注意一下最后的进位flag是否为1,为1则表示最后结点的和是有进位的,需要再向高位进1
代码:
#include <stddef.h> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if (!l1) { return l2; } if (!l2) { return l1; } ListNode *l1Current = l1; ListNode *l2Current = l2; ListNode *result = NULL; ListNode *head = NULL; int flag = 0; //进位 int temp = 0; while (l1Current && l2Current) { temp = l1Current->val + l2Current->val + flag; if (result) { result->next = new ListNode(temp % 10); result = result->next; flag = temp / 10; } else { result = new ListNode(temp % 10); head = result; flag = temp / 10; } l1Current = l1Current->next; l2Current = l2Current->next; } while (l1Current) { temp = l1Current->val + flag; result->next = new ListNode(temp % 10); result = result->next; flag = temp / 10; l1Current = l1Current->next; } while (l2Current) { temp = l2Current->val + flag; result->next = new ListNode(temp % 10); result = result->next; flag = temp / 10; l2Current = l2Current->next; } if (flag) //最后的结点和有进位 { result->next = new ListNode(1); } return head; } };
View Code
网上基本是这个思路
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【002-Add Two Numbers (单链表表示的两个数相加)】
- leetcode 2. Add Two Numbers python实现的理解,结点,单链表的应用,大数,进位的问题
- LeetCode 002 AddTwoNumbers
- [LeetCode]Add Two Numbers
- [LeetCode]Add Two Numbers
- leetcode Add Two Numbers
- [LeetCode]Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode Add Two Numbers
- LeetCode题解:Add Two Numbers
- 2-Add Two Numbers @LeetCode
- [LeetCode - 模拟加法] 2. Add Two Numbers
- LeetCode 2-Add Two Numbers
- leetcode Add Two Numbers
- Leetcode-2 Add Two Numbers
- LeetCode | Add Two Numbers
- leetcode2 Add Two Numbers
- 【Leetcode】Add Two Numbers
- LeetCode Add Two Numbers