66_Plus-One

时间:2023-03-10 05:34:44
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

随机推荐

  1. 调整Linux最大打开文件数

    #!/bin/bash ## 文件数限制 ulimit -n ulimit -Sn ulimit -Hn ## fs.nr_open,进程级别 ## fs.file-max,系统级别 ## 最大文件描 ...

  2. maven项目打jar包

    打包有两种方式: 1.直接 项目--右键--export,选择JAR file打包(不推荐这种方式): 这样直接打的包通过java -jar 会提示“没有主清单属性”,需要修改jar包中的MANIFE ...

  3. c#设计模式之策略者模式(Strategy Pattern)

    场景出发 假设存在如下游戏场景: 1:角色可以装备木剑,铁剑,魔剑3种装备,分别对怪物造成20HP,50HP,100HP伤害(未佩戴装备则无法攻击); 2角色可以向怪物攻击,一次攻击后损失角色所佩戴装 ...

  4. 使用ubuntu搭建时间机器备份服务

    如何在ubuntu下搭建时间备份服务 折腾了很久,终于可以了. 请严格按照下面的方式来操作. 真正明白问题的,可以按照自己的思路来. 我用的是ubnutu 16.04 安装配置netatalk sud ...

  5. IdHTTPServer使用注意问题

    如果在同一电脑上运行多个IdHTTPServer实例,IdHTTPServer使用时候,一定要注意“DefaultPort”属性,其实真正绑定端口是这个属性决定的,所以希望IdHTTPServer绑定 ...

  6. web思维导图(前期)

  7. JSONP前世今生及原理

    https://blog.csdn.net/hansexploration/article/details/80314948 http://www.cnblogs.com/yuzhongwusan/a ...

  8. KVM性能优化学习笔记

    本学习笔记系列都是采用CentOS6.x操作系统,KVM虚拟机的管理也是采用virsh方式,网上的很多的文章都基于ubuntu高版本内核下,KVM的一些新的特性支持更好,本文只是记录了CentOS6. ...

  9. tcping测试端口是否畅通

    https://elifulkerson.com/projects/tcping.php 下载tcping.exe 执行exec文件或者放到C:\Window目录下执行 tcping IP 端口

  10. linux克隆后修配置

    第一步:克隆 第二步:vi /etc/sysconfig/network-scripts/ifcfg-eth0   编辑 DEVICE=eth0 TYPE=Ethernet ONBOOT=yes NM ...