Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
解题思路:整数加1,需要考虑的是进位和最后的结果会不会多一位,比如99,999这样的情况。
package leedcode;
public class plusOne {
private static int[] plus(int[] digits) {
if(digits.length==0||digits==null) return digits;
for (int i = digits.length - 1; i >= 0; i--) { //循环本质上代替了进位
digits[i] = digits[i] + 1;
if (digits[i] == 10)
digits[i] = 0;
else
return digits;
}
int[] res= new int[digits.length + 1];
res[0] = 1;
return res;
}
public static void main(String[] args) {
int[] tes = { 9, 9 };
int[] res = plus(tes);
for (int i = 0; i < res.length; i++) {
System.out.print(res[i] + " ");
}
}
}