leetcode:66.加一

简介: 如果数组中的元素都是9的话,那么原数组就需要扩容一位,否则直接在原基础上修改值即可。

题目描述:


给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/plus-one
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


示例1:


输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。


示例2:


输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。


题目难度:简单


分析:


如果数组中的元素都是9的话,那么原数组就需要扩容一位,否则直接在原基础上修改值即可。代码如下:


java:


class Solution {
    public int[] plusOne(int[] digits) {
      // 表示进位,这里只会加1
        int carry = 1;
        // 用来表示是否需要扩容一位
        boolean b = true;
        // 直接倒序遍历
        for (int i = digits.length - 1; i >= 0; i--) {
            digits[i] += carry;
            // 如果加1以后大于9,那么需要当前位变0,进一位
            if (digits[i] > 9) {
                digits[i] = 0;
            // 否则就可以结束循环,同是标示为false
            } else {
                b = false;
                break;
            }
        }
        if (b) {
          // 如果需要扩容一位的话,我这里直接新建一个数组
          // 只有全是9的才需要扩容,扩容后只有第0位是1,其余都是0
            int[] res = new int[digits.length + 1];
            res[0] = 1;
            return res;
        }
        return digits;
    }
}


python:


class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        flag = True
        for i in range(len(digits) - 1, -1, -1):
            digits[i] += 1
            if digits[i] > 9:
                digits[i] = 0
            else:
                flag = False
                break
        if flag:
            res = [0 for i in range(len(digits) +1 )]
            res[0] = 1
            return res
        return digits


总结:


时间复杂度为O(n)。

目录
相关文章
|
10月前
|
存储
|
2月前
|
SQL 数据采集 算法
LeetCode 题目 66:加一【python5种算法实现】
LeetCode 题目 66:加一【python5种算法实现】
|
3月前
|
存储
LeetCode 66. 加一
LeetCode 66. 加一
29 0
|
11月前
leetcode:66. 加一
函数原型: int* plusOne(int* digits, int digitsSize, int* returnSize) 注:digits是输入的数组,digitsSize是输入数组的大小,returnSize是输出数组的大小
38 0
|
存储 算法
Leetcode——66. 加一
Leetcode——66. 加一
|
存储 Java
力扣66.加一Java
力扣66.加一Java
70 0
|
存储 JavaScript
JS 刷 Leetcode:066. 加一
JS 刷 Leetcode:066. 加一
JS 刷 Leetcode:066. 加一
|
存储 算法 Java
力扣LeetCode初级算法(加一,移动零)(二)
力扣LeetCode初级算法(加一,移动零)
94 0
力扣LeetCode初级算法(加一,移动零)(二)
|
算法 Java
Leetcode 05 ——加一(Java)
Leetcode 05 ——加一(Java)
99 0
Leetcode 05 ——加一(Java)
|
存储
LeetCode 66. 加一
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
74 0