题目地址:Add Two Numbers - LeetCode


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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

最容易想到的解法是把链表转成数字相加后再转成链表。
Python解法如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution:def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:num1, num2 = '', ''while l1 != None:num1 = num1+str(l1.val)l1 = l1.nextwhile l2 != None:num2 = num2+str(l2.val)l2 = l2.nextnum = int(int(num1[::-1])+int(num2[::-1]))root = ListNode(x=0)temp2 = rootwhile num != 0:temp = num % 10temp2.val = tempnum = num//10if num == 0:return roottemp3 = ListNode(x=0)temp2.next = temp3temp2 = temp3return root

这个做法有缺点,那就是如果数很大的话会比较麻烦,虽然Python的int可以无限大,但C语言就不能用这个解法了。
比较好的做法如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:dummy = cur = ListNode(0)carry = 0while l1 or l2 or carry:if l1:carry += l1.vall1 = l1.nextif l2:carry += l2.vall2 = l2.nextcur.next = ListNode(carry%10)cur = cur.nextcarry //= 10return dummy.next

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){struct ListNode *ans = NULL;struct ListNode *change, *az;int temp = 0;while (l1 || l2 || temp){if (l1){temp += l1->val;l1 = l1->next;}if (l2){temp += l2->val;l2 = l2->next;}az = new struct ListNode(0);az->next = NULL;az->val = temp % 10;if (ans == NULL){ans = az;change = ans;}else{change->next = az;change = change->next;}temp = temp / 10;}return ans;}
};

LeetCode 2. Add Two Numbers--C++,Python解法--面试算法题相关推荐

  1. LeetCode 204. Count Primes--从一开始的质数个数--Python解法--面试算法题

    题目地址:Count Primes - LeetCode Count the number of prime numbers less than a non-negative number, n. E ...

  2. LeetCode 230. Kth Smallest Element in a BST--C++,Python解法--面试真题--找二叉树中第K小的元素

    题目地址:Kth Smallest Element in a BST - LeetCode Given a binary search tree, write a function kthSmalle ...

  3. LeetCode 207. Course Schedule--有向图找环--面试算法题--DFS递归,拓扑排序迭代--Python

    题目地址:Course Schedule - LeetCode There are a total of n courses you have to take, labeled from 0 to n ...

  4. leetcode 【 Add Two Numbers 】 python 实现

    题目: You are given two linked lists representing two non-negative numbers. The digits are stored in r ...

  5. LeetCode之Add Two Numbers

    LeetCode之Add Two Numbers 题目:You are given two linked lists representing two non-negative numbers. Th ...

  6. LeetCode 445. Add Two Numbers II

    LeetCode 445. Add Two Numbers II Solution1:我的答案 利用了栈,这样就不用翻转链表了... /*** Definition for singly-linked ...

  7. 【注意】LeetCode 2. Add Two Numbers

    LeetCode 2. Add Two Numbers 这种沙比提怎么都写不对了??? Solution1:学习这种写法 /*** Definition for singly-linked list. ...

  8. 视频教程-大牛带你全面剖析Python高频面试真题-Python

    大牛带你全面剖析Python高频面试真题 毕业于德国奥格斯堡大学计算机系,先从事分布式网络,搜索引擎等领域的设计开发工作,于2017底混入图灵学院,立志挑战传统培训,做中国最好的Python教育 刘英 ...

  9. LeetCode 445. Add Two Numbers II--面试算法题--C++,Python解法

    题目地址:Add Two Numbers II - LeetCode You are given two non-empty linked lists representing two non-neg ...

最新文章

  1. call、bind与apply
  2. mongodb分片介绍—— 基于范围(数值型)的分片 或者 基于哈希的分片
  3. Flask开发微电影网站(十)
  4. openstack 虚拟机如何修改ip地址
  5. vs code html插件_VS插件CodeRush全新发布v20.1.7|支持HTML
  6. nodejs下载安装及配置环境
  7. 不用找,你想要的魏体字体素材都在这里
  8. PPT图片虚化效果要怎样实现?
  9. python+appium出现selenium.common.exceptions.WebDriverException: Message: Method has not yet been imple
  10. python爬取淘宝数据魔方_阅读心得3:《淘宝数据魔方技术架构解析 》
  11. kaggle TMDB5000电影数据分析和电影推荐模型
  12. 呀,要解析的xml文件有1G大,怎么办?
  13. java开发知识总结1
  14. Android旅游自助项目之订票系统订票功能实现
  15. 从erp入门说到产业互联网络
  16. vue写一个翻页的时间插件
  17. JavaScript:实现Sudoku数独游戏算法(附完整源码)
  18. Mac上的经典播放器——Elmedia Player
  19. DRV8870/A4950/AT8870(3.6A单通道刷式直流电机驱动IC)
  20. LLVM每日谈之三十七 Brief Intro to LLVM Backend (HelloLLVM杭州站分享PPT)

热门文章

  1. ISME:西农沈锡辉+韦革宏+王瑶揭示细菌铁获取和外膜囊泡招募新机制
  2. Nature 子刊:三代测序的DNA提取和宏基因组学分析
  3. 223.主成分分析PCA
  4. SBB:无机肥对土壤中固氮菌丰度和群落结构的影响
  5. Gut:北京生科院赵方庆团队揭示人体口腔菌群的稳定性和动态变化规律
  6. Nature综述:微生物的社交网络 - 营养缺陷型如何塑造复杂群落
  7. NC:MetaSort通过降低微生物群落复杂度以突破宏基因组组装难题
  8. R语言使用caret包的preProcess函数进行数据预处理:对所有的数据列进行center中心化、scale标准化(每个数据列减去平均值、除以标准差)、设置参数为center和scale
  9. R语言使用R原生函数plot和lines可视化线图、并使用lty参数自定义线条类型、lwd自定义设置线条的粗细、col参数自定义线条颜色(Change R base plot line types)
  10. R语言apriori算法进行关联规则挖掘(限制规则的左侧或者右侧的内容进行具体规则挖掘)、使用subset函数进一步筛选生成的规则去除左侧规则中的冗余信息、获取更独特的有新意的关联规则