博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode第四题,Add Two Numbers
阅读量:4545 次
发布时间:2019-06-08

本文共 2068 字,大约阅读时间需要 6 分钟。

题目原文:

You are given two linked lists representing two non-negative numbers. 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.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 0 -> 8

题意解析:

给定两个链表表示两个非负数。数字逆序存储,每一个节点包括一个单一的数字。计算两个链表表示的数的和。并以相同格式的链表的形式返还结果。

解法就是直接操作链表相加就能够了。。

代码例如以下:

C++

class Solution {public:	ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {		ListNode * ans = NULL, *last = NULL;		int up = 0;		while (NULL != l1 && NULL != l2) {			int tmp = l1->val + l2->val + up;			up = tmp / 10;			if (NULL == last) {				ans = new ListNode(tmp % 10);				last = ans;			} else			last = pushBack(last, tmp % 10);			l1 = l1->next;			l2 = l2->next;		}		while (NULL != l1) {			int tmp = l1->val + up;			last = pushBack(last, tmp % 10);			up = tmp / 10;			l1 = l1->next;		}		while (NULL != l2) {			int tmp = l2->val + up;			last = pushBack(last, tmp % 10);			up = tmp / 10;			l2 = l2->next;		}		if (0 != up) {			ListNode * l = new ListNode(up);			last->next = l;		}		return ans;	}	ListNode * pushBack(ListNode * last, int val) {		ListNode * l = new ListNode(val);		last->next = l;		return l;	}};

Python

# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = None class Solution:    # @return a ListNode    def addTwoNumbers(self, l1, l2):        carry = 0; head = ListNode(0); curr = head;        while l1 and l2:            Sum = l1.val + l2.val + carry            carry = Sum / 10            curr.next = ListNode(Sum % 10)            l1 = l1.next; l2 = l2.next; curr = curr.next        while l1:            Sum = l1.val + carry            carry = Sum / 10            curr.next = ListNode(Sum % 10)            l1 = l1.next; curr = curr.next        while l2:            Sum = l2.val + carry            carry = Sum / 10            curr.next = ListNode(Sum % 10)            l2 = l2.next; curr = curr.next        if carry > 0:            curr.next = ListNode(carry)        return head.next

水一枚。。。。

转载于:https://www.cnblogs.com/zfyouxi/p/5203352.html

你可能感兴趣的文章
Mac显示器不亮
查看>>
luogu P2312 解方程
查看>>
Cordova开发速记
查看>>
Chrome开发工具
查看>>
MySQL 的 RowNum 实现
查看>>
网络工程师应该掌握的44个路由器问题
查看>>
windows 控制台下运行cl命令
查看>>
(七十八)使用第三方框架INTULocationManager实现定位
查看>>
LeetCode问题:搜索插入位置
查看>>
JVM基础学习之基本概念、可见性与同步
查看>>
UML入门
查看>>
CodeForces - 524F And Yet Another Bracket Sequence
查看>>
python学习笔记-day10-2【多进程,多线程】
查看>>
Atitit 图像处理 平滑 也称 模糊, 归一化块滤波、高斯滤波、中值滤波、双边滤波)...
查看>>
Android Camera——拍照(转自http://vaero.blog.51cto.com/4350852/779942)
查看>>
Java Web项目移植
查看>>
11月的第一天
查看>>
2011简单总结
查看>>
android的Environment类,记录一下
查看>>
工作流Activiti5流程变量 任务变量 setVariables 跟 setVariablesLocal区别
查看>>