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 ...
随机推荐
- linux下如何实现mysql数据库定时自动备份
概述 备份是容灾的基础,是指为防止系统出现操作失误或系统故障导致数据丢失,而将全部或部分数据集合从应用主机的硬盘或阵列复制到其它的存储介质的过程.而对于一些网站.系统来说,数据库就是一切,所以做好 ...
- (转载)office 2003 gaozhi.msi 缺失提示问题修复
某些GHOST版win7,自带office 2003,每次启动word,它都会提示"稿纸没安装"云云,找不到那个文件.可是我搜遍了硬盘,确实没有那个文件.每次都要点取消,这个提示才 ...
- springMvc-对servletApi的支持以及把后台对象以json方式传到前台
1.对servletApi的支持:request.response以及session.cookie的支持 2.把后台代码以json格式向前台输出: 代码: package com.java.contr ...
- <已解决>使用selector设置Button按下松开的样式以及 <item> tag requires a 'drawable' attribute or child tag defining a drawable 报错
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="ht ...
- 未能加载文件或程序集“System.Web.Http, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)解决办法
1.查看引用处是否确实引用, 2.查看<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1& ...
- 2018.2.7 css 的一些方法盒子模型
css 的一些方法 1.盒模型代码简写 盒模型的外边距(margin).内边距(padding)和边框(border)设置上下左右四个方向的边距是按照顺时针方向设置的:上右下左.具体应用在margin ...
- python_25_string
name="my name is 齐志光qizhiguang" print(name.capitalize())#首字母变大写 print(name.count('i'))#统计字 ...
- DongDong坐飞机
题目连接:https://ac.nowcoder.com/acm/contest/904/D 第一次研究了一下这种题型,还是比较好理解的,因为有半价次数的限制,所以要把每一中情况都写出来,dp[现在的 ...
- 模板引擎原理及underscore.js使用
为什么要使用模板引擎 DOM结构简单,完全可以使用DOM方法创建DOM树.$("<td></td").appendTo(); 当页面比较复杂的时候,下面的程序中红 ...
- IBM MQ Explore使用
一,版本说明: 系统:win10.MQ:V9.04 二.关于帮助文档: 1.读了差不多一大半,个人感觉说明的比较生僻,应该是直译过来的.但是还是可以从这里面学一下基本的操作. 2.对于一些基本的操作, ...