算法课程Leetcode作业第三周技术博客
来源:互联网 发布:linux修改字符集编码 编辑:程序博客网 时间:2024/06/07 21:53
算法课程Leetcode作业第三周技术博客
题目:2. Add Two Numbers 难度:medium
题目描述
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.
Examples:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
分析
用线性链表表示加法中的每一位,将不存在的位定为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* l3 = nullptr; ListNode* l3_h = nullptr; int add_1 = 0; int left, right; int result = 0; ListNode* a, *b; a = l1; b = l2; while (a != nullptr || b != nullptr || add_1 != 0) { if (a == nullptr) { left = 0; } else { left = a -> val; } if (b == nullptr) { right = 0; } else { right = b -> val; } result = (right + left + add_1) % 10; if ((left + right + add_1) >= 10) { add_1 = 1; } else { add_1 = 0; } if (l3_h == nullptr) { l3_h = new ListNode(result); l3 = l3_h; } else { l3 -> next = new ListNode(result); l3 = l3 -> next; } if (a != NULL) a = a -> next; if (b != NULL) b = b -> next; } return l3_h; }};
运行结果
这个结果还是令人比较满意的,基本上不需要再优化了。
阅读全文
0 0
- 算法课程Leetcode作业第三周技术博客
- 算法课程Leetcode作业第二周技术博客
- 算法课程Leetcode作业第一周技术博客
- 算法课程Leetcode作业第四周技术博客
- 算法课程第六周Leetcode作业
- Leetcode算法课程第七周作业
- leetcode算法课程第十周博客
- 算法分析与设计课程作业第三周#1
- RFID第三周课程作业
- 第三周博客作业
- [leetcode] 第三周作业
- 第三周算法作业
- 《Web全端工程师就业课程【第三周】》课程作业
- 算法概论第三周作业
- 第三周作业 算法概论
- 算法第三周作业02
- 算法第三周作业01
- 算法第三周作业03
- C#中虚方法总结--2
- Vue2+VueRouter2+Webpack+Axios 构建项目实战2017重制版(二)安装 nodejs 环境以及 vue-cli 构建初始项目
- 进程和线程
- 关于Ubuntu16.04下phpmyadmin出现mbstring错误的正解
- java并发编程--锁和并发的小总结
- 算法课程Leetcode作业第三周技术博客
- 记一次编写python爬虫遇到的问题
- Ubuntu 16.04出现:Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/
- 动态代理
- Android文件权限详解
- HMM
- xpath实例解析
- 上周挖的坑来填了
- C语言,10个值的降序排序