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. solr-DIH:dataimport增量全量创建索引

    索引创建完毕,就要考虑怎么定时的去重建, 除了写solrj,可以定时调用下面两条url进行增量或者全量创建索引   全量:http://ip:port/webapp_name/core_name/da ...

  2. MVC中用jQuery加BootStrap实现动态增加删除文本输入框!

    http://www.freejs.net/article_biaodan_278.html 这是在网上找到方法,我修改了一下实合我的项目,发博只为收藏记录并加深记忆. 修改后效果如下 @model ...

  3. DS作业01--日期抽象数据类型设计与实现

    第六次作业 1.思维导图及学习体会 1.1 思维导图 1.2 学习体会 因为假期里面代码的练习量很小,所以开学来上学期的知识遗忘了很多,刚刚开始写大作业的时候很困难,完全没有思路,后来看了几位同学的代 ...

  4. Wannafly挑战赛26题解

    为啥混进了几道不是魔禁的题--出题人太不敬业了-- 传送门 \(A\) 御坂网络 为啥没有番外个体和整体意志呢 暴力模拟就好了,这个要是都打错我干脆滚回去学文化课算了 //minamoto #incl ...

  5. C++中指针运算

    1,指针可以和数字运算,指针+-整数,如, int num[] = {1,2,3,4,5,6,7,8}; int *p = num; p++; p--; p = p + 3; p = p -3; 数字 ...

  6. Spring-解决请求中文乱码问题

    解决spring请求中文乱码问题 1.web.xml添加编码拦截器 <filter> <filter-name>CharacterEncoding</filter-nam ...

  7. 替代iframe新逻辑

    使用ajax请求.下面是代码逻辑 $.ajax({ url:url, type:'get', dataType: "text", success:function(msg){ $( ...

  8. 理解 atime,ctime,mtime (上)

    理解 atime,ctime,mtime (上) Unix文件系统会为每个文件存储大量时间戳.这意味着您可以使用这些时间戳来查找任意时间访问到的任何文件或目录(读取或写入),更改(文件访问权限更改)或 ...

  9. linux系统解决boot空间不足

    有时候更新Linux系统是会碰到boot空间不足的错误,原因基本上是安装时boot空间设置问题可以通过删除旧的内核来释放boot空间. ubuntu: 1.查看当前使用内核版本号       unam ...

  10. (转)使用VS实现XML2CS

    转自 StackOverFlow Method 1 XSD tool Suppose that you have your XML file in this location C:\path\to\x ...