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. 详解CSS float属性

    CSS中的float属性是一个频繁用到的属性,对于初学者来说,如果没有理解好浮动的意义和表现出来的特性,在使用的使用很容易陷入困惑,云里雾里,搞不清楚状态.本文将从最基本的知识开始说起,谈谈关于浮动的 ...

  2. solr特点六: DIH (从数据源导入数据)

    在这个结构化数据和非结构化数据的数量都很庞大的年代,经常需要从数据库.XML/HTML 文件或其他数据源导入数据,并使数据可搜索.过去,要编写自定义代码才能创建到数据库.文件系统或 RSS 提要的自定 ...

  3. spark-streming 中调用spark-sql时过程遇到的问题

    在spark-streming 中调用spark-sql时过程遇到的问题 使用版本:spark-2.1.0 JDK1.8 1. spark-sql中对limit 的查询结果使用sum() 聚合操作不生 ...

  4. 开源一款强大的文件服务组件(QJ_FileCenter)(系列二 安装说明)

    系列文章 1. 开源一款强大的文件服务组件(QJ_FileCenter)(系列一) 2. 开源一款强大的文件服务组件(QJ_FileCenter)(系列二 安装说明) 3. 开源一款强大的文件服务组件 ...

  5. 企业IT架构转型之道 读书笔记-1.阿里巴巴集团中台战略引发的思考

    前言 1.为什么选择看这本书 2.Supercell公司的开发模式 3.“烟囱式”系统建设模式弊端,及产生这种现象的原因 4.IT人员在企业信息中心的组织职能 一.为什么选择看这本书 多日没有更新博客 ...

  6. WEB文本框提示

    <input type="text" placeholder="文本框提示语" name="version_no"/>

  7. bootstrap table 的searchParam参数传递

    bootstrap table 的searchParam自定义参数传递 Bootstrap Table返回的数据为value 和 rows Long total代表的是多少条(总数)  List< ...

  8. 2018 OCP 052最新题库及答案-4

    4.For which requirement should you configure shared servers? A) accommodating an increasing number o ...

  9. jmeter+ant+jenkins+mac 报告优化(三) 使用命令行执行jmeter方式生成多维度的图形化HTML报告

    1.在构建中填写如下命令: 2.start.sh文件的内容 cd /Applications/apache-jmeter-3.0/bin/ CURTIME=`date +%Y%m%d%H%M` ./j ...

  10. [Objective-C语言教程]继承(25)

    面向对象编程中最重要的概念之一是继承.继承允许根据一个类定义另一个类,这样可以更容易地创建和维护一个应用程序. 这也提供了重用代码功能和快速实现时间的机会. 在创建类时,程序员可以指定新类应该继承现有 ...