LeetCode第四题,Add Two Numbers
2024-08-26 04:29:15
题目原文:
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
水一枚。。。。
最新文章
- [原创]django+ldap实现单点登录(装饰器和缓存)
- 项目里面的某个资源文件(比如plist、音频等)无法使用
- goldengate studio 12.2.1.2.6发布
- win10无法使用内置管理员账户打开应用怎么办
- Oracle11g的安装和基本使用
- 利用mysqldump 将一个表按条件导出数据
- 观察者模式及Java实现例子
- 怎么取消 Windows Server 2012 r2 RDP 限制每个用户只能进行一个会话(转)
- UiAutomator源代码分析之UiAutomatorBridge框架
- [转]Jquery easyui开启行编辑模式增删改操作
- 【Linux/Ubuntu学习8】unbuntu 下播放swf文件
- [转]Oracle学习记录 九 Prc C学习
- 【HDU4366】【DFS序+分块】Successor
- windowIsTranlucent 属性
- USB键盘数据解析
- 驱动07.USB驱动程序
- JQuery中常用的选择器
- Tomcat关闭日志输出
- Python Revisited Day 13 (正则表达式)
- ModelForm 中选择框的数据 以及 instance 参数
热门文章
- 适应多行长文本的Android TextView
- DNS解析服务使用的系统对网站的安全起着很重要的作用
- 普林斯顿大学算法课 Algorithm Part I Week 3 求第K大数 Selection
- WinForm 窗体与窗体相互嵌套
- 配置php中的Oracle扩展
- OC中ARC forbids explicit message send of release错误(转)
- Android消息推送之GCM方式(二)
- 项目积累——Blockingqueue,ConcurrentLinkedQueue,Executors
- Mvc4.0 提取 Cookie 里的东西
- asp.net中自定义验证控件