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.

详见:https://leetcode.com/problems/add-two-numbers/description/

Java实现:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head=null;
ListNode pre=null;
int carry=0;
while(l1!=null||l2!=null){
int val1=l1!=null?l1.val:0;
int val2=l2!=null?l2.val:0;
int val=val1+val2+carry;
carry=val/10;
val%=10;
ListNode cur=new ListNode(val);
if(head==null){
head=cur;
}
if(pre!=null){
pre.next=cur;
}
pre=cur;
l1=l1!=null?l1.next:null;
l2=l2!=null?l2.next:null;
}
if(carry!=0){
ListNode l=new ListNode(carry);
pre.next=l;
}
return head;
}
}

python:

# 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:
head,pre,carry=None,None,0
while l1 or l2:
val1,val2=0,0
if l1:
val1=l1.val
l1=l1.next
if l2:
val2=l2.val
l2=l2.next
val=val1+val2+carry
carry=val//10
val%=10
cur=ListNode(val)
if not head:
head=cur
if pre:
pre.next=cur
pre=cur if carry:
pre.next=ListNode(carry) return head

最新文章

  1. android 各种xml资源的引用方式
  2. 一道 google曾出过的笔试题:编程实现对数学一元多项式的相加和相乘操作(1)
  3. 2016 Al-Baath University Training Camp Contest-1 C
  4. cocos2d-x 开发中的小问题 在xcode4环境下
  5. Codeforces 10C Digital Root 法冠军
  6. Objective-C Runtime 运行时之六:拾遗(转载)
  7. Web Scraper使用
  8. java模拟数据库缓存
  9. Selinux是什么?
  10. C# Unity的使用
  11. WC.exe【C】
  12. ZZNUOJ 2022 摩斯密码
  13. Dubbo -- 系统学习 笔记 -- 配置
  14. 1142 奖学金 sort做法
  15. EasyPlayerPro安卓流媒体播放器实现Android H.265硬解码流程
  16. 对于KVO,你真的了解么?
  17. spring mvc 入门程序
  18. java中创建User Libray
  19. (转)Nmap命令的29个实用范例
  20. 利用 getsockname 和 getpeername 来获取某一个链接的本地地址和远端地址

热门文章

  1. bzoj 2096 [POI2004]ZAW——二进制枚举
  2. Java常见设计模式之观察者模式
  3. Java中是构造器创建对象吗?
  4. Java探索之旅(1)——概述与控制台输入
  5. js刷新页面方法大全(转)
  6. Spring开发包介绍
  7. C++中栈结构建立和操作
  8. 22、IDP-ASE
  9. 利用css实现鼠标经过元素,下划线由中间向两边展开
  10. vue,webpack,node间的关系