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
随机推荐
- TSQL--标示列、GUID 、序列
--1. IDENTIY 列不能为空,不能设默认值,创建后不能使用ALTER TABLE TableName ALTER COLUMN修改,每张表只能有一个自增列--2. 查看当前值:SELECT I ...
- winform 版本号比较
Version now_v = new Version(strval); Version load_v = new Version(model.version.ToString()); if (now ...
- java.lang.IllegalArgumentException: No converter found for return value of type: class com.smart.result.Page
今天学习了一下spring boot 中的mybatis,用mybatis来增删改查用户,获取用户,添加用户,修改用户,删除用户,修改用户,都是可以的,但是获取带分页的用户列表,一直抛出这个java. ...
- Skyline桌面二次开发之路径漫游(C#)
所谓路径漫游:即创建一个动态对象和一条由多点组成的线,然后让动态对象沿着线飞行 首先绘制一条线,实际上路径漫游是不需要绘制线的,我这里只是为了确认动态对象是否沿着线路在飞行,代码如下: //绘制路径 ...
- ASP.NET基于NPOI导出数据
using System; using System.Collections; using System.Collections.Generic; using System.IO; using Sys ...
- sql数据库 大小查询
select * from sys.master_files where name='CODA_PRD_Catalog' 12416*8/1024=(m)
- POJ 2069 模拟退火算法
Super Star Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 6422 Accepted: 1591 Spec ...
- 常见的HTTP请求应答返回码列表
200 OK 请求成功.一般用于GET与POST请求 300 Multiple Choices 多种选择.请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例 ...
- Drupal 远程命令执行漏洞(CVE-2018-7600)
名称: Drupal 远程命令执行漏洞 CVE-ID: CVE-2018-7600 Poc: https://paper.seebug.org/578/ EXPLOIT-DB: https://www ...
- 修改linux的文件时,如何快速找到要修改的内容
♦ 在linux系统下,找到需要修改的文件.使用cd+目录的命令进行文件所在的目录,使用ls命令查看是否有该文件. ♦ 使用vim+文件名,打开该文件 ♦ 快速在文件中找到需要修改的地方.如我们需要修 ...