66. Plus One

Easy

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.
package leetcode.easy;

public class PlusOne {
@org.junit.Test
public void test() {
int[] digits11 = { 1, 2, 3 };
int[] digits21 = { 4, 3, 2, 1 };
int[] digits12 = plusOne(digits11);
int[] digits22 = plusOne(digits21); for (int i = 0; i < digits12.length; i++) {
System.out.print(digits12[i]);
}
System.out.println(); for (int i = 0; i < digits22.length; i++) {
System.out.print(digits22[i]);
}
System.out.println();
} public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] != 9) {
digits[i]++;
break;
} else {
digits[i] = 0;
}
} if (digits[0] != 0) {
return digits;
} else {
int[] result = new int[digits.length + 1];
result[0] = 1;
return result;
}
}
}

LeetCode_66. Plus One的更多相关文章

随机推荐

  1. Java8 中的 Optional 相关用法

    基本方法: ofNullable() 为可能 null 的值创建一个 Optional 实例,  然后可以对该实例遍历/过滤, 判断是否存在,或者为空时执行.. ifPresent(...) 如果值存 ...

  2. test20181102 空间复杂度 和 test20181030 数独

    空间复杂度 考场做法 前有时间复杂度,后有空间复杂度. 但是这题不会有CE情况,所以较为好写. 就用map存复杂度,单层循环就搞定了. 至于判断维度的方法,我是用快读从字符串中读入. 然后不管常数,把 ...

  3. 在 windows 上安装 git 2.15

    下载 by win 下载地址:https://git-scm.com/download/win 如下图.选择对应的版本下载: 安装 by win 1.双击下载好的git安装包.弹出提示框.如下图: 2 ...

  4. 洛谷P2051 中国象棋【dp】

    题目:https://www.luogu.org/problemnew/show/P2051 题意:n*m的格子里放炮,使他们不能互相攻击. 如果两个炮在同一行同一列并且中间还有一个棋子的话就可以攻击 ...

  5. ajax当有返回值时

    当ajax方法里面有return 值时,无法使用两种精简版的只能使用经典版 因为ajax 方法时异步的,正确的方式时使用经典版中async:false 设置为同步 默认为true  是异步 正确代码如 ...

  6. 关于 sublime 的插件 AdvancedNewFile 新建文件/文件夹 插件

    新建文件的插件: 快捷键:Ctrl + N 路径:当前目录下进行创建:js/index.js      表示在当前js目录下面创建index.js box      表示直接在当前目录下面创建一个bo ...

  7. guava字符串工具--------Joiner 根据给定的分隔符把字符串连接到一起

    public class JoinerTest { public static void main(String args[]){ //1.将list字符串集合,以,形式转为字符串 List<S ...

  8. MongoDB 3.4 功能改进一览

    MongoDB 3.4 已经发布,本文主要介绍 3.4 版本在功能特性上做的改进,内容翻译自 [https://docs.mongodb.com/manual/release-notes/3.4/?_ ...

  9. QLocalSocket

    QIODevice做为QLocalSocket的父类 在Qt中,提供了多种IPC方法.看起来好像和Socket搭上点边,实则底层是windows的name pipe.这应该是支持双工通信的 QLoca ...

  10. [Python]闭包的理解和使用

    闭包广泛使用在函数式编程语言中,虽然不是很容易理解,但是又不得不理解. 闭包是什么? 在一些语言中,在函数中可以(嵌套)定义另一个函数时,如果内部的函数引用了外部的函数的变量,则可能产生闭包.闭包可以 ...