Plus One
- leetcode: Plus One | LeetCode OJ
- lintcode:
The digits are stored such that the most significant digit is at the head of the list.
Example
Given [9,9,9] which represents 999, return [1,0,0,0].
/**
* @return the result
*/
public int[] plusOne(int[] digits) {
return plusDigit(digits, 1);
}
private int[] plusDigit(int[] digits, int digit) {
// regard digit(0~9) as carry
int carry = digit;
int[] result = new int[digits.length];
for (int i = digits.length - 1; i >= 0; i--) {
carry = (digits[i] + carry) / 10;
}
if (carry == 1) {
int[] finalResult = new int[result.length + 1];
finalResult[0] = 1;
return finalResult;
}
return result;
}
}
源码中单独实现了加任何数(0~9)的私有方法,更为通用,对于末尾第一个数,可以将要加的数当做进位处理,这样就不必单独区分最后一位了,十分优雅!