题目
大致思路
本题的技巧点在与对数组的熟悉程度,新建数组的默认数值为0,因此我们碰到999的数组元素时,直接扩充一位,并且将数组首元素复制为1即可。
其余的非全部为9的数组元素,只需要将9的位置赋值为0即可,0-8的元素,直接加1就可以了。
简单来讲:逢9规0,其余加1,全9扩充。
代码实现
package com.immunize.leetcode.delete_oneplus;
/**
* 加一:相当于实现一个竖式的加法计算:分析的结果为:逢9规0,其余加1,全9扩充。
*
* @author Mr IMMUNIZE
*
*/
public class OnePlus {
public int[] plusOne(int[] digits) {
// 倒序遍历,相当于竖式加法。
int n = digits.length;
for (int i = n - 1; i >= 0; i--) {
// 非9加1
if (digits[i] < 9) {
digits[i]++;
return digits;
}
// 逢9置0
digits[i] = 0;
}
// 全部为9,则需要数组扩充1位
int[] result = new int[n + 1];
result[0] = 1;
return result;
}
}
----------------------------------------------------------------------------
package com.immunize.leetcode.delete_oneplus;
import java.util.Scanner;
/**
* Test:进行测试即可。
*
* @author Mr IMMUNIZE
*
*/
public class OnePlusTest {
public static void main(String[] args) {
// 输入数组,以逗号隔开
System.out.println("请输入数组:");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] c = s.split(",");
int[] array = new int[c.length];
for (int i = 0; i < c.length; i++) {
array[i] = Integer.parseInt(c[i]);
}
OnePlus op = new OnePlus();
for (int j = 0; j < op.plusOne(array).length; j++) {
System.out.print(op.plusOne(array)[j] + " ");
}
}
}