美文网首页
[LeetCode 66] Plus One (easy)

[LeetCode 66] Plus One (easy)

作者: 灰睛眼蓝 | 来源:发表于2019-08-13 14:37 被阅读0次

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.

Solution

  1. 从最后一位开始加,可以认为+ 1 == 从一开始的进位carry = 1.
  2. 先得到加上carry 以后的值,carry重置为0; 如果结果 >= 10, 那么当前位结果为0, carry == 1;否则当前位结果 == digit[index] + carry
  3. 如果全部扫描完了,carry还是为1,那么说明input是 99, 999这种情况。那么直接生成一个新的array,长度为digits.length + 1, 再把首位设为1,返回这个新的array即可。
  4. 否则返回digits
class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0)
            return digits;
        
        // handle case less than like 999, 99 which after + 1 the result wont has more digits
        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            int temp = digits[i] + carry;
            carry = 0;
            
            if (temp >= 10) {
                digits[i] = 0;
                carry = 1;
            } else {
                digits [i] = temp;
            }
        }
        
        // handle special case 999, 99, after + 1, it will have 1 more digit
        if (carry == 1) {
            int[] newDigits = new int[digits.length + 1];
            newDigits[0] = 1;
            
            return newDigits;
        }
        
        return digits;
    }
}

相关文章

  • LeetCode 66-70

    66. Plus One[https://leetcode-cn.com/problems/plus-one/] ...

  • [LeetCode 66] Plus One (easy)

    Given a non-empty array of digits representing a non-nega...

  • 66. Plus One

    66. Plus One 题目:https://leetcode.com/problems/plus-one/ 难...

  • LeetCode每日练习(66、724、189)

    66-加一[https://leetcode-cn.com/problems/plus-one/] 输入:digi...

  • LeetCode:66. 加一

    问题链接 66. 加一[https://leetcode-cn.com/problems/plus-one] 问题...

  • Leetcode-66 加一

    66. 加一[https://leetcode-cn.com/problems/plus-one/] 解题思路 1...

  • 66. 加一

    题目地址(66. 加一) https://leetcode.cn/problems/plus-one/[https...

  • LeetCode 66 [Plus One]

    原题 给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。该数字按照大小进行排列,最大的数在列...

  • 【Leetcode】66—Plus One

    一、题目描述 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数组...

  • [easy][Array]66.Plus One

    原题是: Given a non-negative integer represented as a non-em...

网友评论

      本文标题:[LeetCode 66] Plus One (easy)

      本文链接:https://www.haomeiwen.com/subject/iuovjctx.html