66_Plus-One
66_Plus-One
Description
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Solution
Java solution
class Solution {
public int[] plusOne(int[] digits) {
int n = digits.length;
for (int i=n-1; i>=0; i--) {
if (digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;
}
int[] newNum = new int[n+1];
newNum[0] = 1;
return newNum;
}
}
Runtime: 0 ms
Python solution 1
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
i = len(digits) - 1
while digits[i] == 9 and i>=0:
digits[i] = 0
i -= 1
if i < 0:
return [1] + digits
else:
digits[i] += 1
return digits
Runtime: 44 ms
Python solution 2
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
num = 0
for i in range(len(digits)):
num += digits[i] * pow(10, len(digits)-1-i)
return [int(n) for n in str(num+1)]
Runtime: 40 ms
Python solution 3
class Solution:
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
return [int(n) for n in str(int(''.join(map(str, digits))) + 1)]
Runtime: 40 ms
随机推荐
- yum反查某个命令或so库在哪个包里面
yum whatprovides "*/XXX.so.1"
- .net core 自制错误日志
前言 之前.net framework用的ErrorLog帮助类,对于监控错误形成日志,内容非常清晰,想在.net core2.2中继续用,但是有很多不一样的地方,所以想总结一下. 首先需要HttpC ...
- WPF 降低.net framework到4.0
1. 问题背景 由于xp系统上面最高只能安装.net framework 4.0,所以公司项目需要将原来项目的.net framework版本降低到4.0,具体的降版本很简单,只要把项目属性中的目标框 ...
- LightOJ 1220 Mysterious Bacteria(唯一分解定理 + 素数筛选)
http://lightoj.com/volume_showproblem.php?problem=1220 Mysterious Bacteria Time Limit:500MS Memo ...
- jQuery中的each, data, 插件
一. each() $(' ').each(function (){...}) jQuery.each(collection, callback(indexInArray, valueOfEleme ...
- Android 音视频开发入门指南
Android 音视频从入门到提高 —— 任务列表 http://blog.51cto.com/ticktick/1956269(以这个学习为基础往下面去学习) Android 音视频开发学习思路-- ...
- shell、cmd、dos和脚本语言区别和联系
问题一:DOS与windows中cmd区别 在windows系统中,“开始-运行-cmd”可以打开“cmd.exe”,进行命令行操作. 操作系统可以分成核心(kernel)和Shell(外壳)两部 ...
- 【OCP-12c】2019年CUUG OCP 071考试题库(76题)
76.View the exhibit and examine the description of the DEPARTMENTSand EMPLOYEEStables. The retrieve ...
- luoguP4647 [IOI2007] sails 船帆
https://www.luogu.org/problemnew/show/P4647 首先发现答案与顺序无关,令 $ x_i $ 表示高度为 $ i $ 的那一行帆的个数,第 $ i $ 行对答案的 ...
- BZOJ 3110 [Zjoi2013]K大数查询 (CDQ分治+树状数组)
题目描述 有N个位置,M个操作.操作有两种,每次操作如果是1 a b c的形式表示在第a个位置到第b个位置,每个位置加入一个数c如果是2 a b c形式,表示询问从第a个位置到第b个位置,第C大的数是 ...