Leetcode 初探
来源:互联网 发布:淘宝能注销账号吗 编辑:程序博客网 时间:2024/05/16 11:26
Add Two Numbers
第一次在leetcode上面做题,选了两道最简单的题目来试试手,回忆一下cpp的写法。写了一个暑假的python之后,在cpp语法上稍微有点不太习惯,还好,做完前两道题就上手了。
这里主要讲一讲Question2.
题目原意:
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
这种题目以前做的也挺多,就是两个链表相加,注意进位问题。
第一次写出来的代码是这样的(确实有点久没写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* ans = new ListNode(l1->val + l2->val); ListNode* pre = ans; ListNode* cur1 = l1->next, *cur2 = l2->next; int carry = 0; Carry(ans, carry); while (cur1 != NULL || cur2 != NULL) { ListNode* node = new ListNode(0); if (cur1 != NULL && cur2 != NULL) { node->val = cur1->val + cur2->val + carry; cur1 = cur1->next; cur2 = cur2->next; } else if (cur1 != NULL) { node->val = cur1->val + carry; cur1 = cur1->next; } else if (cur2 != NULL) { node->val = cur2->val + carry; cur2 = cur2->next; } pre->next = node; pre = node; Carry(node, carry); } if (carry == 1) pre->next = new ListNode(1); return ans; } void Carry(ListNode*& node, int &carry) { if (node->val > 9) { carry = 1; node->val -= 10; } else carry = 0; }};
看了答案后,发现答案的写法确实简洁:
/** * 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* dummyHead = new ListNode(0); ListNode* p = l1, * q = l2, *cur = dummyHead; int carry = 0; while (p != NULL || q != NULL) { //利用三元表达式处理if语句 int x = (p != NULL)? p->val: 0; int y = (q != NULL)? q->val: 0; int sum = x + y + carry; //利用除法和取余处理多种情况 carry = sum / 10; cur->next = new ListNode(sum % 10); cur = cur->next; if (p != NULL) p = p->next; if (q != NULL) q = q->next; } //最后处理进位 if (carry) cur->next = new ListNode(1); return dummyHead->next; }};
阅读全文
0 0
- Leetcode 初探
- (LeetCode初探)从A+B开始
- Leetcode 412 Fizz Buzz及vector初探
- 初探
- 初探PHP5
- jdbc初探......
- STL初探
- HiveMind初探
- 初探人工智能
- 初探人工智能
- SQLDMO初探
- 初探maven
- Hibernate初探
- COM初探
- 初探RMI
- Ajax初探
- HiveMind初探
- 初探JFreeChart
- 解决前台js 传数组数据到后台,后台只能获取数组的第一个值,后面的值都有问题
- [自制操作系统] 连续页分配释放&kmalloc/kfree
- spark2.2.0源码学习过程记录:Day7
- 三种循环
- 常见的磁盘调度算法
- Leetcode 初探
- MySQL知识点总结
- 1019. 数字黑洞 (20)
- 【多校联合】(HDU6095)Rikka with Competition
- spark2.2.0源码学习过程记录:Day8
- 探索Map接口
- spark2.2.0源码学习过程记录:Day9
- 修改Linux用户名
- spark2.2.0源码学习过程记录:Day10