题目要求:
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.
大致意思就是用一个数组表示一个数字,比如89,用数组arr表示为:arr[0]=8,arr[9],题目要求就是对这个数加一,然后处理好进位问题。
so easy, 直接上代码:
public int[] plusOne(int[] digits) {
int num = 1;
for(int i=digits.length-1; i>=0; i--) {
int sum = digits[i] + num;
digits[i] = sum % 10;
num = sum / 10;
}
if(num > 0) {
digits = Arrays.copyOf(digits, digits.length+1);
digits[0] = num;
}
return digits;
}