LeetCode - 2. Add Two Numbers
来源:互联网 发布:美国 动画专业 知乎 编辑:程序博客网 时间:2024/04/28 08:02
LeetCode - 2. Add Two Numbers
题目:
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
题目大意:
给你两个链表,链表中存放的是非负数。链表中的数字是逆序存放,并且每个节点都只有一位数字。求讲这两个数字相加得到的链表
考点:
- 链表操作
- n位数相加,考虑进位
- 两个数相加,可能位数不同
- 如果最后还有一个进位,需要再添加一个节点保存进位数字
代码:
/** * 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; ListNode* p1 = l1; ListNode* p2 = l2; ListNode* result = NULL; ListNode* pResult = NULL; int jinwei = 0; while(p1 !=NULL || p2 != NULL) { int num1 = (p1 == NULL ? 0 : p1->val); int num2 = (p2 == NULL ? 0 : p2->val); int val = (num1 + num2 + jinwei) % 10; jinwei = (num1 + num2 + jinwei) / 10; if(result == NULL) { result = new ListNode(val); pResult = result; } else { ListNode* temp = new ListNode(val); pResult->next = temp; pResult = pResult->next; } p1 = (p1 == NULL? NULL: p1->next); p2 = (p2 == NULL? NULL: p2->next); } if( jinwei > 0){ ListNode* temp = new ListNode(jinwei); pResult->next = temp; pResult = temp->next; } return result; }};
0 0
- [LeetCode]2.Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode --- 2. Add Two Numbers
- [Leetcode] 2. Add Two Numbers
- 【leetcode】2. Add Two Numbers
- leetcode 2. Add Two Numbers
- LeetCode-2.Add Two Numbers
- [leetcode] 2. Add Two Numbers
- 【LeetCode】2. Add Two Numbers
- LeetCode - 2. Add Two Numbers
- LeetCode 2.Add Two Numbers
- LeetCode 2. Add Two Numbers
- Leetcode 2. Add Two Numbers
- 2. Add Two Numbers LeetCode
- leetcode 2. Add Two Numbers
- LeetCode-2. Add Two Numbers
- LeetCode 2. Add Two Numbers
- 2. Add Two Numbers----LeetCode
- Treasure the new start, freshmen!
- [HDU]ACM Steps-Chapter One-Section 1
- i-jetty-3.1编译小结
- 【OpenGL】000 Visual Studio 2015 搭建OpenGL环境
- Shortest Prefixes (POJ_2001) 字典树
- LeetCode - 2. Add Two Numbers
- Java中synchronized如何正确同步
- HttpServletRequest对象(一)
- poj 2752 Seek the Name, Seek the Fame【kmp】
- C++中友元函数
- php的学习笔记之面向对象(三) 构造函数
- python字符串操作
- 小试循环
- C++ vector变量等导致内存泄露问题的解决方法