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

随机推荐

  1. Redis配置参数汇总

    ==配置文件全解=== ==基本配置daemonize no 是否以后台进程启动databases 16 创建database的数量(默认选中的是database 0) save 900 1 #刷新快 ...

  2. oracle中的序列,可以解决自增各种编号自动增长问题,说一下我的小问题。

    1.生成0001-9999的编码 //在PL/sql中 创建一个序列 Create sequence seq_cdptIncrement by 1 --自增数Start with 1 --开始累加数M ...

  3. Let it crash philosophy part II

    Designing fault tolerant systems is extremely difficult.  You can try to anticipate and reason about ...

  4. Luogu4551 最长异或路径

    题目链接:戳我 emmmmmmmmmm异或一个数两次等于没有操作对吧...所以我们按照前缀的异或和,建一个01trie.....然后之后.....直接在树上贪心地找能和它每一位不一样的数....然后. ...

  5. php实现socket简单的例子

    一.Socket简介 1.socket只不过是一种数据结构 2.使用这个socket数据结构去开始一个客户端和服务器之间的会话 3.服务器是一直在监听准备产生一个新的会话.当一个客户端连接服务端,它就 ...

  6. 2018-2019-2 20165219《网络对抗技术》Exp0 Kali安装 Week1

    2018-2019-2 20165219<网络对抗技术>Exp0 Kali安装 Week1 安装Kali 在官网下载,然后将解压后的文件导入 输入username和password 共享文 ...

  7. LOJ#6049. 「雅礼集训 2017 Day10」拍苍蝇(计算几何+bitset)

    题面 传送门 题解 首先可以用一个矩形去套这个多边形,那么我们只要枚举这个矩形的左下角就可以枚举完所有多边形的位置了 我们先对每一个\(x\)坐标开一个\(bitset\),表示这个\(x\)坐标里哪 ...

  8. 打开SQL Server2000企业管理器时候提示“MMC 无法创建管理单元 ”

    今天上午在打开SQL Server 2000 企业管理器时候提示“MMC 无法创建管理单元”错误.

  9. 看个AV也中招之cve-2010-2553漏洞分析

    试想:某一天,你的基友给你了一个视频文件,号称是陈老师拍的苍老师的老师题材的最新电影.avi,你满心欢喜,在确定文件格式确实为avi格式后,愉快的脱下裤子准备欣赏,打开后却发现什么也没有,而随后你的基 ...

  10. [Objective-C语言教程]指针(15)

    Objective-C中的指针简单易学.使用指针可以更轻松地执行某些Objective-C编程任务,并且在不使用指针的情况下无法执行其他任务(如动态内存分配). 所以有必要学习指向成为一个完美的Obj ...