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

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. 《剑指offer》【调整数组顺序使奇数位于偶数前面】(python版)

    题目描述: 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分 思路: 我认真看了一下,题目应该是要求在原地调整,所以这里不能再 ...

  2. 毛毛虫组【Beta】Scrum Meeting 2

    第二天 日期:2019/6/24 前言 第二次会议: 时间:6月24日 地点:教10-503 内容:此次会议主要是进一步完善系统,分配进行文档的准备工作. 1.1 今日完成任务情况以及遇到的问题. 今 ...

  3. macbook pro开机键盘键盘和触摸板没反应问题

    今天遇到开机键盘和触摸板没反应的问题,打电话给售后,他叫我插一个usb外置键盘,开机时按shift+alt+control+电源键开机,突然发现可以了,这bug我也是醉了

  4. HTML5中最看重的理念“语义化”相比HTML有什么区别?

    这里搜集整理了一些语义化标签方面的问题和解答,以供大家参考. 语义化这个概念应该说是伴着HTML5应运而生,那么什么是HTML5中所谓的语义化? 简单来说就是:描述内容的含义(meaning) 比如说 ...

  5. Zimber 8.8.12卸载后重新安装报错解决办法

    1.1  zimber故障处理步骤 1.1.1  现象描述 Running Post Installation Configuration: /opt/zimbra/bin/zmlocalconfig ...

  6. relu函数为分段线性函数,为什么会增加非线性元素

    relu函数为分段线性函数,为什么会增加非线性元素 我们知道激活函数的作用就是为了为神经网络增加非线性因素,使其可以拟合任意的函数.那么relu在大于的时候就是线性函数,如果我们的输出值一直是在大于0 ...

  7. Python9-MySQL-MySQL存储过程-视图-触发器-函数-day45

    视图:某个查询语句设置别名,日后方便使用 CREATE VIEW v1 as SELECT * FROM student WHERE sid >10 -创建: create view 视图名称 ...

  8. Green Space【绿色空间】

    Green Space Living in an urban area with green spaces has a long-lasting positive impact on people's ...

  9. Python 有序字典简介

    Table of Contents 1. 有序字典-OrderedDict简介 1.1. 示例 1.2. 相等性 1.3. 注意 2. 参考资料 有序字典-OrderedDict简介 示例 有序字典和 ...

  10. postgreysql

    基础 syntax * \help 生成所有的pg命令 * abort 终止事务/work * alter aggregate 修改聚合函数的定义 ALTER AGGREGATE name ( typ ...