【LeetCode】 66. Plus One 加一(Easy)(JAVA)

【LeetCode】 66. Plus One 加一(Easy)(JAVA)

题目地址: https://leetcode.com/problems/plus-one/

题目描述:

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.

题目大意

给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

解题方法

比较简单,直接遍历,判断是否需要进位即可

class Solution {
    public int[] plusOne(int[] digits) {
        int carry = 1;
        for (int i = digits.length - 1; i >= 0; i--) {
            carry += digits[i];
            digits[i] = carry % 10;
            carry /= 10;
        }
        if (carry <= 0) return digits;
        int[] res = new int[digits.length + 1];
        res[0] = carry;
        for (int i = 0; i < digits.length; i++) {
            res[i + 1] = digits[i];
        }
        return res;
    }
}

执行用时 : 0 ms, 在所有 Java 提交中击败了 100.00% 的用户
内存消耗 : 37.3 MB , 在所有 Java 提交中击败了 5.11% 的用户

扫描二维码关注公众号,回复: 9882150 查看本文章
发布了81 篇原创文章 · 获赞 6 · 访问量 2272

猜你喜欢

转载自blog.csdn.net/qq_16927853/article/details/104893373
今日推荐