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