这又过了一周了,总感觉刷这个好花时间呀。每次都一两个小时。让我不好安排时间。应该是我太菜了。对,没错,就是这样

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的更多相关文章

  1. LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters

    LeetCode(2) || Add Two Numbers && Longest Substring Without Repeating Characters 题记 刷LeetCod ...

  2. LeetCode:1. Add Two Numbers

    题目: LeetCode:1. Add Two Numbers 描述: Given an array of integers, return indices of the two numbers su ...

  3. [LeetCode] 445. Add Two Numbers II 两个数字相加之二

    You are given two linked lists representing two non-negative numbers. The most significant digit com ...

  4. LeetCode 面试:Add Two Numbers

    1 题目 You are given two linked lists representing two non-negative numbers. The digits are stored in ...

  5. LeetCode #002# Add Two Numbers(js描述)

    索引 思路1:基本加法规则 思路2:移花接木法... 问题描述:https://leetcode.com/problems/add-two-numbers/ 思路1:基本加法规则 根据小学学的基本加法 ...

  6. [Leetcode Week15] Add Two Numbers

    Add Two Numbers 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/add-two-numbers/description/ Descrip ...

  7. [LeetCode] 2. Add Two Numbers 两个数字相加 java语言实现 C++语言实现

    [LeetCode] Add Two Numbers 两个数字相加   You are given two non-empty linked lists representing two non-ne ...

  8. [LeetCode] 2. Add Two Numbers 两个数字相加

    You are given two non-empty linked lists representing two non-negative integers. The digits are stor ...

  9. LeetCode之Add Two Numbers

    Add Two Numbers 方法一: 考虑到有进位的问题,首先想到的思路是: 先分位求总和得到 totalsum,然后再将totalsum按位拆分转成链表: ListNode* addTwoNum ...

随机推荐

  1. RF的一些技术知识

    1. dBm 定义的是 miliwatt(毫瓦特).0 dBm=1mw:    dBw 定义 watt.0 dBW = 1 W =1000 mw = 10lg(1000/1)dBm=30dbm. dB ...

  2. linux 命令——2 cd (转)

    Linux cd 命令可以说是Linux中最基本的命令语句,其他的命令语句要进行操作,都是建立在使用 cd 命令上的. 所以,学习Linux 常用命令,首先就要学好 cd 命令的使用方法技巧. 1.  ...

  3. 使用Eclipse连接SAP云平台上的HANA数据库实例

    SAP云平台(Cloud Platform)上的HANA数据库实例有两种方式访问: 1. 通过SAP云平台的基于网页版的Development Tool:SAP HANA Web-Based Deve ...

  4. 【BZOJ4571】[SCOI2016] 美味(主席树)

    点此看题面 大致题意: 给你一个序列\(a\),然后每次询问\(max_{i=l}^r(a_i+x)\ xor\ b\). 大致思路 首先,我们要知道一个简单的性质:位运算时位与位之间是互不影响的. ...

  5. 解决linux系统CentOS下调整home和根分区大小《转》

    转自http://www.php114.net/2013/1019/637.html 目标:将VolGroup-lv_home缩小到20G,并将剩余的空间添加给VolGroup-lv_root   1 ...

  6. 支持向量机: Maximum Margin Classifier

    支持向量机即 Support Vector Machine,简称 SVM .我最开始听说这头机器的名号的时候,一种神秘感就油然而生,似乎把 Support 这么一个具体的动作和 Vector 这么一个 ...

  7. CUDA:Supercomputing for the Masses (用于大量数据的超级计算)-第二节

    原文链接 第二节:第一个内核 Rob Farber 是西北太平洋国家实验室(Pacific Northwest National Laboratory)的高级科研人员.他在多个国家级的实验室进行大型并 ...

  8. Xcode Warning: “no rule to process file

    警告⚠️: warning: no rule to process file '/Users/Kingdev/Desktop/Git/finance_iOS/finance/Library/MBpro ...

  9. 第31题:LeetCode946. Validate Stack Sequences验证栈的序列

    题目 给定 pushed 和 popped 两个序列,只有当它们可能是在最初空栈上进行的推入 push 和弹出 pop 操作序列的结果时,返回 true:否则,返回 false . 示例 1: 输入: ...

  10. 3- vue django restful framework 打造生鲜超市 - model设计和资源导入

    3- vue django restful framework 打造生鲜超市 - model设计和资源导入 使用Python3.6与Django2.0.2(Django-rest-framework) ...