LeetCode题解:Add Two Numbers
来源:互联网 发布:it外包公司 编辑:程序博客网 时间:2024/05/22 01:52
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
思路:
中小学竞赛题。
题解:
/** * 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) { ListNode* i1 = l1; ListNode* i2 = l2; ListNode* ret = new ListNode(0); ListNode* ret_last = ret; bool carry = false; while(i1 != nullptr || i2 != nullptr) { int s = 0; if (i1 != nullptr) s = i1->val, i1 = i1->next; if (i2 != nullptr) s += i2->val, i2 = i2->next; s += carry; ret_last->next = new ListNode(s % 10); ret_last = ret_last->next; carry = (s >= 10); } if (carry) ret_last->next = new ListNode(1); ret_last = ret->next; delete ret; return ret_last; }};
- LeetCode题解:Add Two Numbers
- LeetCode题解:Add Two Numbers
- [LeetCode] Add Two Numbers题解
- LeetCode 题解(26): Add Two Numbers
- LeetCode题解 || Add Two Numbers 问题
- [Leetcode题解]002 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
- LeetCode题解-2-Add Two Numbers
- LeetCode Algorithms 2. Add Two Numbers 题解
- LeetCode 2. Add Two Numbers 题解
- 2. Add Two Numbers LeetCode题解
- LeetCode题解(2)--Add Two Numbers
- LeetCode题解(Golang实现)--Add Two Numbers
- LeetCode题解 #2 Add Two Numbers
- Error setting expression 'ldstock.ldstocktype.ldstockTypeCode' with value '[Ljava.lang.String;@10f40
- zabbix 监控squid 命中率、cachesize等相关
- iOS App 转移 图文详解
- ps aux指令詳解
- 《Windows via C/C++》学习笔记(四)用户模式的“线程同步”
- LeetCode题解:Add Two Numbers
- 页面访问日志表
- romInit.s源码分析
- 测试一下代码片
- 牛顿法求平方根
- 关于Android ArrayList与json数据格式的转化
- hdu 4778Gems Fight!
- 算法分析基础---渐进符号和递归式分析
- Kohana数据操作CRUD之插入、更新、删除