[LeetCode]--66. 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.题目的意思就是把这个数组代

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.

题目的意思就是把这个数组代表的大数字加一,然后考虑进位的问题,如果都是9就要考虑加一位的问题。这是一个处理大数据的办法,当数字超出了整型的长度,我们就可以用这种办法。我们需要处理的就是进位问题。

public int[] plusOne(int[] digits) {
        int flag = 1, sum;
        for (int i = digits.length - 1; i >= 0; i--) {
            sum = digits[i] + flag;
            digits[i] = sum % 10;
            flag = sum / 10;
        }
        // 如果还有进位,我们就得在数组最前面加一个了
        if (flag == 1) {
            int[] newDigits = new int[digits.length + 1];
            newDigits[0] = 1;
            for (int i = 0; i < digits.length; i++) {
                newDigits[i + 1] = digits[i];
            }
            return newDigits;
        }
        return digits;
    }

其实呢,进位只有当时9的时候才会发生,所以我们也可以判断是否为9这样处理。

public int[] plusOne(int[] digits) {
        for (int i = digits.length - 1; i >= 0; i--)
            if (digits[i] == 9) {
                digits[i] = 0;
            } else {
                digits[i]++;
                return digits;
            }
        int[] newDigits = new int[digits.length + 1];
        newDigits[0] = 1;
        for (int i = 0; i < digits.length; i++) {
            newDigits[i + 1] = digits[i];
        }
        return digits;
    }
目录
相关文章
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
130 0
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode Contest 178-1368. 使网格图至少有一条有效路径的最小代价 Minimum Cost to Make at Least One Valid Path in a Grid
LeetCode 233. Number of Digit One
给定一个整数 n,计算所有小于等于 n 的非负整数中数字 1 出现的个数。
192 0
LeetCode 233. Number of Digit One
|
存储 Python
LeetCode 66. Plus One
给定表示非负整数的非空数字数组,加上整数的1。 存储数字使得最高有效数字位于列表的开头,并且数组中的每个元素包含单个数字。 您可以假设整数不包含任何前导零,除了数字0本身。
226 0
LeetCode 66. Plus One
|
存储 算法
LeetCode 66. 加一 Plus One
LeetCode 66. 加一 Plus One
|
存储
LeetCode 66 Plus One(加一)(vector)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50564455 翻译 给定一个以一系列数字表示的非负数,将其加一并转换成数字。
937 0
|
Unix Shell Linux
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
本文提供了几个Linux shell脚本编程问题的解决方案,包括转置文件内容、统计词频、验证有效电话号码和提取文件的第十行,每个问题都给出了至少一种实现方法。
277 6
LeetCode刷题 Shell编程四则 | 194. 转置文件 192. 统计词频 193. 有效电话号码 195. 第十行
|
搜索推荐 索引 Python
【Leetcode刷题Python】牛客. 数组中未出现的最小正整数
本文介绍了牛客网题目"数组中未出现的最小正整数"的解法,提供了一种满足O(n)时间复杂度和O(1)空间复杂度要求的原地排序算法,并给出了Python实现代码。
387 2

热门文章

最新文章