LeetCode每日一题--加一
2020-03-15 18:21
169 查看
【前言】坚持日更LeetCode刷题系列
不积跬步,无以至千里;不积小流,无以成江海。愿与诸君共勉!
【题目】66.加一
题目描述:给定一个由
整数组成的
非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储
单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
你可以假设数组中无重复元素。
示例:
示例 1: 输入: [1,2,3] 输出: [1,2,4] 解释: 输入数组表示数字 123。 示例 2: 输入: [4,3,2,1] 输出: [4,3,2,2] 解释: 输入数组表示数字 4321。 示例 3: 输入: [9] 输出: [1,0] 解释:输入数组表示数字9
思路一:很容易我们可用想到暴力求解的方法,即将列表中的数字转化为原来的数字后加一,再求出结果后的每位数码,并逆序输出即可。具体代码如下:
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ sum1 = 0 for i in range(len(digits)): sum1 = sum1*10+digits[i] sum1 = sum1+1 list2 = [] while sum1>0: list2.append(sum1%10) sum1 = sum1//10 return list2[::-1]
运行结果:
思路二:采用递归的思想(操作上采用循环遍历的方式),从末尾数开始判断(digits[i]+1 % 10)如果为0,则上一位产生进位,继续进行相同的判断,直到判断不为0。注意当数字为99,999类型时,需要在列表增加一个新元素1。具体代码如下:
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ for i in range(len(digits)-1,-1,-1): digits[i] = digits[i]+1 #可以想下为什么把digits[i]+1放在此处 if(digits[i]%10==0): digits[i] = 0 else: return digits if(digits[0]==0): #如果首位为0,则证明该数字为99,999类型,因此需要在首位插入一个1 digits.insert(0,1) return digits
运行结果:
关于其中一些知识的链接:
思路三:利用python中int类型和str类型互化求解。具体代码(参考自LeeCode评论区某前辈)如下:
class Solution: def plusOne(self, digits): ''' :type digits: List[int] :rtype :List[int] ''' d = int(''.join([str(i) for i in digits]))+1 return [int(i) for i in str(d) ]
运行结果:
分享就到这里了,欢迎大家一起交流讨论。
注明:
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/plus-one
- 点赞 2
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【leetcode每日一题】NO86.Partition List
- [LeetCode]11. Plus One加一运算
- LeetCode每日一题 004 字符串相乘
- leetcode 每日一题 34. Search for a Range
- leetcode:20 Valid Parentheses-每日编程第三十七题
- leetcode Two Sum 每日一题 (。・∀・)ノ゙嗨
- Reverse Integer Leetcode 每日一题 ↖(^ω^)↗
- 【leetcode每日一题】24.Swap Nodes in Pairs
- LeetCode每日一题——T7. 整数反转(易):反转字符串
- LeetCode每日一题——T20. 有效的括号(易):栈、哈希表
- LeetCode每日一题(2018-01-11)
- 每日一题 LeetCode 有效的数字 Python实现
- 每天一道LeetCode-----将用数组表示的整数加一,两个用字符串表示的(二进制)数相加
- 再从萌新开始-Leetcode每日题解-287. Find the Duplicate Number
- LeetCode每日一题:207.课程表
- leetcode每日一练
- LeetCode每日一题——T9. 回文数(易):字符串切片
- 每日一练之poor pigs【leetcode No.458】——猪测毒问题
- 每日一题:Leetcode 面试题13.机器人的运动范围
- 【leetcode每日一题】NO83.Remove Duplicates from Sorted List