链接: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.
分析:
没别的方法,就是加,但是要注意进1位,总感觉这不是算法题,是细节题.
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;
}
}
}