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. TFS签入代码时,自动修改工作项的状态为“已解决”

    Visual Studio中有一个很酷的功能,就是签入代码到TFS库时,可以关联相应的工作项,实现代码与工作项(需求.任务.Bug等)的关联,从而实现代码的跟踪. 在关联工作项的过程中,如果工作项具备 ...

  2. Tempdb--临时对象缓存

    SQL Server删除一个临时对象时,不移除该对象的条目,当再次使用时,就无须重新创建临时对象,SQL Server为临时对象缓存一个数据页和一个IAM页,并回收剩余页,如果临时表的大小超过8MB, ...

  3. VUE 学习笔记 三 模板语法

    1.插值 a.文本 数据绑定最常见的形式就是使用“Mustache”语法 (双大括号) 的文本插值 <span>Message: {{ msg }}</span> v-once ...

  4. DataTable转List<T>

    /// <summary> /// DataTable转List<T> /// </summary> public static class TableToList ...

  5. 在Windows Server 2008上部署免费的https证书

    背景 后web时代,https加密的重要性不言而喻.主流浏览器均对http站点标记不安全,敦促web服务提供商尽快升级至https. 原先的https证书多由各大域名服务商提供,动辄成千上万的部署证书 ...

  6. EF按时间范围条件查询

    查询今日数据 db.Table.Where(d => System.Data.Entity.DbFunctions.DiffDays(d.Time, DateTime.Now) == )

  7. Linq与数据库的连接显示查询(一)

    使用linq查询sql数据库是首先需要创建一个 linq  to  sql 类文件 创建linq  to  sql的步骤: 1在Visual  Studio 2015开发环境中建立一个目标框架 Fra ...

  8. django drf JWT

    建议使用djangorestframework-jwt或者djangorestframework_simplejwt,文档为 https://github.com/GetBlimp/django-re ...

  9. UWP开发砸手机系列(一)—— Accessibility

    因为今天讨论的内容不属于入门系列,所以我把标题都改了.这个啥Accessibility说实话属于及其蛋疼的内容,即如何让视力有障碍的人也能通过声音来使用触屏手机……也许你这辈子也不会接触,但如果有一天 ...

  10. Python 错误和异常小结

    1.Python异常类 Python是面向对象语言,所以程序抛出的异常也是类.常见的Python异常有以下几个,大家只要大致扫一眼,有个映像,等到编程的时候,相信大家肯定会不只一次跟他们照面(除非你不 ...