LeetCode66

力扣66题:加一

题目描述:

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

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/plus-one
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路如下图:

全9则数组长度加一,首位置1,并返回;

遍历遇9变0,非9加一,停止遍历并返回;

在这里插入图片描述

代码如下:

class Solution {
    public int[] plusOne(int[] digits) {
        int n = digits.length;
        for (int i = n - 1; i >= 0; --i) {
            if (digits[i] < 9) {
                digits[i]++;
                return digits;
            }
            digits[i] = 0;
        }
        //能出for循环说明是需要进位的情况
        int[] res = new int[n + 1];
        res[0] = 1;
        return res;
    }
}

记录:

//判断整数的位数
int digit= (int)Math.floor(Math.log10(Math.abs(num)) +1);
/**
 * 将正整数-->相对应的数组;如:1234-->[1,2,3,4]
 */
int num = 99998;
int digit = (int) Math.floor(Math.log10(Math.abs(num)) + 1);//判断整数的位数
int[] res = new int[digit];//整数转为数组
for (int i = digit-1; i >= 0; i--) {
    res[i] = num % 10;
    num /= 10;
    System.out.printf("res[%d]=%d\n",i,res[i]);
}

猜你喜欢

转载自blog.csdn.net/Miss_croal/article/details/130386888