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

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. 用log4net快速构建asp.net 异常日志

    log4net是一个非常完善的日志组件. 有着强大的可配置性. 有助于提高开发效率 .log4net是apache组织开发的日志组件, 同其姐妹log4j一样, 是一个开源项目. 可以以插件的形式应用 ...

  2. Android商城开发系列(十一)—— 首页秒杀布局实现

    首页秒杀布局如下图: 布局使用的是LinearLayout和RecyclerView去实现,新建seckkill_item.xml,代码如下所示: <?xml version="1.0 ...

  3. 多进程——waitpid()函数的小例子

    本例中使用fork()创建一个子进程,然后让子进程暂停5s,接下来对原有的父进程使用waitpid()函数,利用WNOHANG使父进程不会阻塞每隔一秒判断子进程是否退出. #include" ...

  4. top命令交互快捷键

    #toptop - :: up :, users, load average: 0.17, 0.12, 0.14 Tasks: total, running, sleeping, stopped, z ...

  5. 【洛谷1580】yyy loves Easter_Egg I(字符串处理题)

    点此看题面 大致题意: 略.(一道模拟题,自己去看题面吧) 几个字符数组函数 纯粹是一道字符串处理题,就当是学了一下各种与字符数组相关的函数吧! \(gets()\):这个是比较常用的函数,就是读入一 ...

  6. 【BZOJ1057】[ZJOI2007] 棋盘制作(单调栈的运用)

    点此看题面 大致题意: 给你一个\(N*M\)的\(01\)矩阵,要求你分别求出最大的\(01\)相间的正方形和矩形(矩形也可以是正方形),并输出其面积. 题解 这题第一眼看去没什么思路,仔细想想,能 ...

  7. 2018.6.6 基于Oracle数据库的航天信息系统JDBC练习

    综合练习 一.语言和环境 A.实现语言 Java B.环境要求 JDK 6.0及其以上版本.MyEclipse7.5及其以上版本.Oracle11g.PL/SQL Developer 二.功能要求 开 ...

  8. 多线程:InterlockedIncrement

    1.InterlockedIncrement保护多线程中操作的整数. #include <stdio.h> #include <windows.h> volatile long ...

  9. 操作系统(5)_内存管理_李善平ppt

    i386先通过段是管理,在通过页是管理

  10. Math类小结

    package com.swift; public class MathDemo { public static void main(String[] args) { // TODO Auto-gen ...