Tuesday, April 1, 2014

Plus One @LeetCode

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.
package leetcode;
/**
* Solution: Assume there's carry, and check if there's carry in the last step,
* if so, create new array, the first element will be 1.if not, just return digits(already add 1).
* Optimization: just break if carry != 1. Don't need to loop from (n-1..0)
*
* My inefficient way. like Add Binary, Add Two Numbers. create int[digits.length + 1].
* add 1, and at the last step, check if first int is equals to 1. if not. cope the rest, if so, return.
* @author jeffwan
* @date Apr 1, 2014
*/
public class PlusOne {
public int[] plusOne(int[] digits) {
int carry = 1;
for (int i = digits.length - 1; i >= 0 && carry > 0; i--) {
int sum = carry + digits[i];
digits[i] = sum % 10;
carry = sum / 10;
}
if (carry == 0) {
return digits;
}
int[] result = new int[digits.length + 1];
result[0] = 1;
for (int i = 1; i < result.length; i++) {
result[i] = digits[i - 1];
}
return result;
}
}
view raw PlusOne.java hosted with ❤ by GitHub

No comments:

Post a Comment