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
随机推荐
- 如何在TortoiseGit中使用ssh-keygen生成的key
再windows 用TortoiseGit 时,git clone 项目时 提示 "Couldn't load this key (OpenSSH SSH-2 private key),如下 ...
- Sql语法高级应用之六:如何在Sql语句中如何使用TRY...CATCH
TRY...CATCH使用范例 BEGIN TRY //逻辑语句块 END TRYBEGIN CATCH //Catch异常处理块 SET @msg = ERROR_MESSAGE(); PRINT ...
- 源码编译安装MySQL-5.6/mysql-5.6.39------踩了无数坑,重装了十几次服务器才会的,不容易啊!
1.切换到src目录 cd /usr/local/src/ 2. 下载mysql免编译二进制包 免编译的mysql二进制包5.6源码包: wget http://mirrors.163.com/mys ...
- 实例的初始化由JVM装载类的时候进行,保证了线程的安全性
在23种设计模式中,单例是最简单的设计模式,但是也是很常用的设计模式.从单例的五种实现方式中我们可以看到程序员对性能的不懈追求.下面我将分析单例的五种实现方式的优缺点,并对其在多线程环境下的性能进行测 ...
- C++多线程编程一
1.C++多线程初步: #include <iostream> #include <thread> #include <Windows.h> using names ...
- delphi 10.2 ----简单的递归函数例子求和
unit Unit10; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, Syste ...
- 类型转换:static_cast、reinterpret_cast等
一.隐式类型转换 系统自动进行,不需要程序开发人员介入. int m = 3 + 45.6;// 48 把小数部分截掉,也属于隐式类型转换的一部分 double b = 3 + 45.6; // 48 ...
- CentOS下安装Docker
简介:本篇文章介绍如何在CentOS系统下面安装docker系统. 官方文档:https://docs.docker.com/install/linux/docker-ce/centos/ Docke ...
- java 实现七大基本排序算法
一. 选择排序 /** * 选择排序: int arr[] = { 5, 6, 2, 7, 8, 6, 4 }; * * 第0趟 5 2 6 7 6 4 8 第1趟 2 5 6 6 4 7 8 第2趟 ...
- spark中资源调度任务调度
在spark的资源调度中 1.集群启动worker向master汇报资源情况 2.Client向集群提交app,向master注册一个driver(需要多少core.memery),启动一个drive ...