Leetcode 66. Plus One

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

用一个数组代表一个数字,求+1以后的值,数组返回形式。
加1以后两种情况:1、产生进位,高一位的数继续加1;2、没有进位,高位的数保持原样。
注意:99或999这样各位都是9的数,最后的结果会比原来的数多一位。
自己的思路是用out作为进位标志,如果一个循环结束,out还表示有进位,证明是99这样的情况,需要再增加一位。

public int[] plusOne(int[] digits) {
    if (digits == null || digits.length == 0) {
        int[] res = new int[1];
        res[0] = 1;
        return res;
    }

    List<Integer> list = new LinkedList<>();
    boolean out = true;
    for (int i = digits.length - 1; i >= 0; i--) {
        if (out) {
            if (digits[i] == 9) {
                list.add(0, 0);
            } else {
                list.add(0, digits[i] + 1);
                out = false;
            }
        } else {
            list.add(0, digits[i]);
        }
    }
    if (out) {
        list.add(0, 1);
    }

    int[] res = new int[list.size()];
    for (int i = 0; i < res.length; i++) {
        res[i] = list.get(i);
    }

    return res;
}

自己用了一个list,所以空间复杂度是O(n)。翻看discuss,了解到自己处理的有些多余了,因为仅仅是99这样的情况会多一位,其他时候如果不产生进位,则直接修改传入的原数组再返回就可以了。

public int[] plusOne1(int[] digits) {
    if (digits == null || digits.length == 0) {
        return new int[]{1};
    }
    for (int i = digits.length - 1; i >= 0; i--) {
        if (digits[i] < 9) {
            digits[i]++;
            return digits;
        } else {
            digits[i] = 0;
        }
    }
    int[] res = new int[digits.length + 1];
    res[0] = 1;
    return res;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 题目 Given a non-negative integer represented as a non-empt...
    persistent100阅读 163评论 0 0
  • 原题 给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。该数字按照大小进行排列,最大的数在列...
    Jason_Yuan阅读 271评论 0 0
  • 题目 题目大意:将一个数字加1,这个数字的每一位存放在数组里。 直接模拟相加的过程就好。 代码如下:
    沉默的叔叔阅读 527评论 0 0
  • 文/谢雨乔 谨以此文献给那些还处在暗恋中的朋友,愿有一天,你爱的人终将爱你。 “不表白永远不可能”【郑大某男生写给...
    文西里阅读 588评论 1 4