Plus One

https://leetcode.com/problems/plus-one/

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

算法描述

这个题目需要注意的地方是假设数组的长度是n,那么一个数的最高有效位是数组的第0个数,数组的最低有效位是数组的第n-1个数。

  1. new一个ArrayList为resDigits
  2. 按照n-1, n-2, ..., 0这样的顺序读取数组的值,首先将第n-1个数和1相加值为sum
  3. 如果有进位(也即sum == 10),那么resDigits就加个0元素,接着原数组余下元素,即第n-2, n-3, ..., 0位的数值跳到步骤2)继续执行;

    如果没有进位,那么resDigits就加上sum,并且数组的余下元素也加到resDigits中
  4. 因为得到的resDigits的第0个数是最低有效位,因此按照题目的要求,把resDigits倒过来。

程序代码

public class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
if (digits == null || length == 0) {
return null;
} List<Integer> resDigits = new ArrayList<Integer>();
int n = digits.length - 1;
Boolean flag = true;
do {
if (flag) {
int sum = digits[n--] + 1;
if (sum == 10) {
resDigits.add(0);
flag = true;
} else {
resDigits.add(sum);
flag = false;
}
} else {
resDigits.add(digits[n--]);
}
}while(n >= 0); if (flag) {
resDigits.add(1);
} int[] newDigits = new int[resDigits.size()];
for (int i = resDigits.size() - 1; i >= 0; i--) {
newDigits[newDigits.length - 1 - i] = resDigits.get(i);
} return newDigits;
}
}

随机推荐

  1. C#更改win7系统时间的代码,以及为什么更改不成功

    我在用C#更改win7系统的时间时(必须用管理员的权限,点击要运行程序,鼠标右键“以管理员权限运行”),下面列出了3张图片,使用第一张的代码执行不成功,使用第二张图片可以执行成功,第三张图片是说明原因 ...

  2. 一些java的书籍

    netty in action 中文版:http://pan.baidu.com/s/1pLnEKZL spring security-3.0.1:http://pan.baidu.com/s/1bp ...

  3. 三、动态SQL语句

    //备注:该博客引自:http://limingnihao.iteye.com/blog/106076 有些时候,sql语句where条件中,需要一些安全判断,例如按某一条件查询时如果传入的参数是空, ...

  4. CentOS7 Debian 8 安装VMware-tools

    如在安装过程中碰到未找到gcc 或者 kernel headers的可按以下方案解决,适用任意版本 CentOS 7 1. Update the kernel: $ yum update kernel ...

  5. docker 使用

    https://www.digitalocean.com/community/tutorials/how-to-use-the-digitalocean-docker-application http ...

  6. 回车键和button按钮都绑定同一个事件,如何避免按回车的时候button重复点击

    保存一个全局变量,用来记录Button的焦点状态 <button onclick="login();" onfocus="window.buttonIsFocuse ...

  7. 拖拽改变div的大小

    拖拽改变div的大小 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type&qu ...

  8. VC连接mysql数据库错误:libmysql.lib : fatal error LNK1113: invalid machine 解决方法

    VC连接MySQL的配置过程在上一篇博文中,不过当你设置好,以为万事大吉的时候,运行却出现这个错误:libmysql.lib : fatal error LNK1113: invalid machin ...

  9. wxPython简单入门

    wxPython简介 wxPython 是 Python 语言的一套优秀的 GUI 图形库,允许 Python 程序员很方便的创建完整的.功能键全的  GUI 用户界面. wxPython 是作为优秀 ...

  10. Python学习一入门

    一.打印Hello和多行文本 print 打印 后跟单引号或者双引号 多行:3个单引号或者3个双引号 二.算术运算 2.1.加减乖法 默认1/2=0 如果需要小数运算,则需要一个运算术上加.或者.0 ...