鏈接:https://leetcode.com/problems/plus-one/
原題:
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.
分析:
沒別的方法,就是加,但是要注意進(jìn)1位僚害,總感覺這不是算法題,是細(xì)節(jié)題.
public class Solution {
public int[] plusOne(int[] digits) {
if (digits.length == 0) {
return new int[]{1};
}
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int value = digits[i] + carry;
carry = value/10;
digits[i] = value%10;
if(carry == 0) {
break;
}
}
if(carry == 1) {
int[] one = new int[digits.length+1];
one[0] = 1;
for(int i=1;i<digits.length+1;i++) {
one[i] = digits[i-1];
}
return one;
} else {
return digits;
}
}
}