LeetCode-2:Add Two Numbers (列表做整数相加)
来源:互联网 发布:消防四知四会 编辑:程序博客网 时间:2024/06/06 12:31
题目:
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 -> 8Explanation: 342 + 465 = 807.
问题解析:
给定两个链表分别代表两个非负整数。数位以倒序存储,并且每一个节点包含一位数字。将两个数字相加并以链表形式返回。
链接:
https://leetcode.com/problems/add-two-numbers/description/
思路标签:
数据结构:List
解答:
1. 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 preHead(0), *p = &preHead; int extra = 0; while(l1 || l2 || extra){ int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; extra = sum / 10; p->next = new ListNode(sum % 10); p = p->next; l1 = l1 ? l1->next : l1; l2 = l2 ? l2->next : l2; } return preHead.next; }};
2. python
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 root = n = ListNode(0) while l1 or l2 or carry: v1 = v2 = 0 if l1: v1 = l1.val l1 = l1.next if l2: v2 = l2.val l2 = l2.next carry, val = divmod(v1+v2+carry, 10) n.next = ListNode(val) n = n.next return root.next
C++相关:
List:http://blog.csdn.net/yas12345678/article/details/52601578
阅读全文
0 0
- LeetCode-2:Add Two Numbers (列表做整数相加)
- LeetCode 2 : Add Two Numbers ---- 单链表相加
- 新手做LeetCode 2 Add Two Numbers
- Add Two Numbers Leetcode 链表相加
- Leetcode Add two numbers链表相加
- [Leetcode]Add Two Numbers链表数相加
- 【LeetCode】链表相加 Add Two Numbers
- leetcode Add Two Numbers 两个数相加
- 大整数相加链表实现(Add Two Numbers)
- 445. Add Two Numbers II | 链表的整数相加
- LeetCode 2 - Add Two Numbers
- LeetCode 2: Add Two Numbers
- Leetcode: Add Two Numbers (2)
- [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
- Centos7 pip jupyter
- Spring Boot 整合 Mybatis Annotation 注解的完整 Web 案例
- 当云计算遇到足球,会撞出怎样的黑科技火花
- 在Linux系统的命令行中为MySQL创建用户的方法
- Java 8 习惯用语,第 6 部分 为什么完美的 lambda 表达式只有一行
- LeetCode-2:Add Two Numbers (列表做整数相加)
- Linux网络编程基础---字节序
- 送外卖
- 吴恩达深度学习课程心得
- 欢迎使用CSDN-markdown编辑器
- MySql学习--数据表的基本操作--创建数据表
- Java并发编程------volatile关键字
- QT控件大全三QLed
- Android性能优化实战(一)----App启动时间优化