LeetCode——Problem2:Add Two Numbers
这又过了一周了,总感觉刷这个好花时间呀。每次都一两个小时。让我不好安排时间。应该是我太菜了。对,没错,就是这样
1、题目
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
2、Python解法
我想的是先把链表转化为数字相加,再把结果数字转化为链表
以下是我写的全部代码
#!/usr/bin/python3
# -*- coding: utf-8 -*-
#@author: Albert
#@Time: 2018/8/13 class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2): #求解
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
number1=self.getNumber(l1)
number2=self.getNumber(l2)
number=number1+number2
l=self.num2LinkedLists(number)
return l def getNumber(self,l): #将链表转化为数字
number = 0
item = 1
while(item):
number = number+l.val*item
item=item*10
l=l.next
if l==None:
item=0
return number
def num2LinkedLists(self,num): #将数字转化为链表 value=num%10
rest=int(num/10)
l=ListNode(value)
if rest!=0:
value = rest % 10
rest = int(rest / 10)
l.next=ListNode(value)
temp=l.next
while(rest!=0):
value=rest%10
rest=int(rest/10)
temp.next=ListNode(value)
temp=temp.next
return l def makeLinkedList(n): #将一个列表数字转化为题目要求的链表,按照个位,十位,百位的顺序
l = ListNode(n[0])
l.next = ListNode(n[1])
temp = l.next
for i in n[2:]:
temp.next = ListNode(i)
temp = temp.next
return l l1=makeLinkedList([2,4,3])
l2=makeLinkedList([5,6,4]) a=Solution()
l=a.addTwoNumbers(l1,l2)
number=a.getNumber(l)
print(number)
接下来看大神解法
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = l1
carry = 0
while 1:
temp_sum = l1.val + l2.val + carry
l1.val = temp_sum % 10
carry = temp_sum // 10
if not (l1.next and l2.next):
break
l1 = l1.next
l2 = l2.next
if not (l1.next or l2.next):
if carry == 1:
l1.next = ListNode(1)
return head
lr = l2 if l1.next == None else l1
l1.next = lr.next
while l1.next:
l1 = l1.next
temp_sum = l1.val + carry
l1.val = temp_sum % 10
carry = temp_sum // 10
if carry == 1:
l1.next = ListNode(1)
return head
我第二个想到的算法是这个,就是借用小学算加法的思路。设置一个进位。
3、C语言解法
我尝试了,但是结构体的基础有点差。没有运行成功。这就直接贴大神的解法了。运行时间20ms
#define MAKE_NODE (struct ListNode *)malloc(sizeof(struct ListNode))
struct ListNode *add_one(struct ListNode *);
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *p = l1, *q = l2, *r = NULL;
int carry = ;
struct ListNode *nh = NULL;
long sum = ;
while (p != NULL && q != NULL) {
struct ListNode *new = (struct ListNode *) malloc(sizeof(struct ListNode));
sum = p -> val + q -> val + carry;
if (sum >= ) {
sum -= ;
carry = ;
}
else carry = ;
new -> val = sum;
new -> next = NULL;
if (nh == NULL) {
nh = new;
r = nh;
} else {
r -> next = new;
r = new;
}
p = p -> next;
q = q -> next;
}
if (p != NULL && q == NULL) {
if (!carry) {
r -> next = p;
return nh;
} //other we have a carry
p = add_one(p);
r -> next = p;
return nh;
}
else if (p == NULL && q != NULL) {
if (!carry) {
r -> next = q;
return nh;
}
q = add_one(q);
r -> next = q;
return nh;
} if (carry > ) {
r -> next = MAKE_NODE;
(r -> next) -> val = ;
(r -> next) -> next = NULL;
return nh;
}
return nh;
}
struct ListNode *add_one(struct ListNode *h) {
struct ListNode *p = h, *prev = NULL; int carry = ;
while (h != NULL) { h -> val += carry;
if (h -> val > ) {
carry = ;
h -> val -= ;
}
else {
carry = ;
}
prev = h;
h = h -> next;
}
if (carry > ) {
struct ListNode *new = MAKE_NODE;
new -> val = ;
new -> next = NULL;
prev -> next = new;
}
return p;
}
其中的算法都是按照加法的进位
我还是C语言基础都忘的差不多了,没有写对。
主要是这个申请内存。(struct ListNode *)malloc(sizeof(struct ListNode))
其实他这个算法稍微麻烦了点。又用了一个新的add_one函数。如果l1,l2数目不一样。直接在后面的时候还直接进位,假设另一个为0就好啦。
最近事贼多。唉~愁人。想上研的时候跨专业,需要补习的东西还有很多呀~
LeetCode——Problem2:Add Two Numbers的更多相关文章
- LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters
LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...
- LeetCode:1. Add Two Numbers
题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...
- [LeetCode] 445. Add Two Numbers II 两个数字相加之二
You are given two linked lists representing two non-negative numbers. The most significant digit com ...
- LeetCode 面试:Add Two Numbers
1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...
- LeetCode #002# Add Two Numbers(js描述)
索引 思路1:基本加法规则 思路2:移花接木法... 问题描述:https://leetcode.com/problems/add-two-numbers/ 思路1:基本加法规则 根据小学学的基本加法 ...
- [Leetcode Week15] Add Two Numbers
Add Two Numbers 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/add-two-numbers/description/ Descrip ...
- [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现
[LeetCode] Add Two Numbers 两个数字相加 You are given two non-empty linked lists representing two non-ne ...
- [LeetCode] 2. Add Two Numbers 两个数字相加
You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...
- LeetCode之Add Two Numbers
Add Two Numbers 方法一: 考虑到有进位的问题,首先想到的思路是: 先分位求总和得到 totalsum,然后再将totalsum按位拆分转成链表: ListNode* addTwoNum ...
随机推荐
- ssh免密钥登录一例问题
今天遇到一个奇怪的问题,在同一机器上创建的普通用户使用 ssh-copy-id -i .ssh/id_rsa.pub root@192.168.3.254 建立与root用户的免密钥通信,结果死活还是 ...
- JavaScript_HTML DEMO_3_节点
创建新的HTML元素 删除已有的HTML元素 <body> <div id="div1"> <p id="p1">这是一个段 ...
- cms-详细页面-3
1.设置上一条.下一条数据 2.使用昌言插件 3.点击链接帖子的访问数加一 1.在mapper中设置分页: <?xml version="1.0" encoding=&quo ...
- Hbase各种查询总结
运用hbase好长时间了,今天利用闲暇时间把Hbase的各种查询总结下,以后有时间把协处理器和自定义File总结下. 查询条件分为: 1.统计表数据 2,hbase 简单分页 3,like 查询 4 ...
- Go - 环境安装
目录 你好,Go语言 环境安装 目录结构 命令 开发工具 学习网址 小结 你好,Go语言 Go 是一个开源的编程语言,它能让构造简单.可靠且高效的软件变得容易. 因工作需要,准备入坑,先从环境安装开始 ...
- java 学习集锦
java学习系列 http://www.cnblogs.com/skywang12345/category/455711.html
- cloudera manager的卸载以及重新安装
1 卸载cloudera 参照 http://www.cnblogs.com/chenfool/p/3738540.html Cloudera 的官方介绍: http://www.cloudera.c ...
- edge不能上网-代码 INET_E_RESOURCE_NOT_FOUND
这个问题 ,网上有很多解决方法,我基本都测试了一遍,可是我都没有用 情况:首先,我开始的时候是可以用的,然后在公司,开了代理,就不能使用了,这是我之后多次尝试发现的,所以你也遇到和我一样的情况不必惊慌 ...
- 七、MySQL 选择数据库
MySQL 选择数据库 在你连接到 MySQL 数据库后,可能有多个可以操作的数据库,所以你需要选择你要操作的数据库. 从命令提示窗口中选择MySQL数据库 在 mysql> 提示窗口中可以很简 ...
- java设计模式1--单例模式
1:单例模式简介 单例模式是一种常用的软件设计模式,它确保某个类只有一个实例,而且自行实例化并向整个系统提供唯一的实例.总而言之就是在系统中只会存在一个对象,其中的数据是共享的 特点: 单例类只能有一 ...