LeetCode 2. Add Two Numbers
来源:互联网 发布:淘宝商城品牌旗舰店 编辑:程序博客网 时间:2024/06/07 18:04
LeetCode 2. Add Two Numbers
- LeetCode 2 Add Two Numbers
- 题目
- 注意事项
- 过程
- C代码
【题目】
You are given two non-empty linked lists representing two non-negative integers. 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. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
注意事项
输入输出都是逆向的,所以要注意进位应该是给右边的数加而不是给左边的数加。 另外,要考虑输入的两个ListNode的长度可能不一样,比如(2->5) + (5->6->4) = (7>1->5)。 以及输出的长度大于两个输入的长度,比如(3->4)+(4->9) = (7->1->3)
过程
我用一个“While”语句,当L1、L2还没有到尽头或者还有进位的时候就进入循环,下一项的 val 等于L1->val , L2->val 以及进位的和,然后取10的余数。注意要把curr、L1、L2指向下一个未处理节点。为了代码简洁,我使用了比较多的三元操作符 条件 ? 结果1 : 结果2
这道题目还是比较简单的,只要注意上面几个问题,不要用错指针便可以简单解答出来,下面是我的代码
C++代码
/** * 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 pre(0),*curr = ⪯ int flag = 0; while(l1 || l2 || flag){ int temp = (l1 ? l1->val : 0) +(l2 ? l2->val : 0)+flag; flag = temp>9 ? 1 : 0; curr->next = new ListNode(temp % 10); curr = curr->next; l1 ? l1=l1->next : 0; l2 ? l2=l2->next : 0; } return pre.next; }};
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
- ELK日志系统:Elasticsearch + Logstash + Kibana 搭建教程
- 原子性操作和volatile
- jvm中方法执行
- 构建Docker平台【第一篇】环境准备
- Great Classical Musics For All of U.
- LeetCode 2. Add Two Numbers
- 打造黑苹果(六)设置无线网卡上网
- JavaWeb之JSP
- 阿里云服务器低jdk版本配置多项目
- Leetcode解题笔记(5)
- 对SolrCloud集群Collection进行手动二次Sharding
- Codeforces 779D String Game 二分
- sudo权限
- plist文件操作