Given a number represented as an array of digits, plus one to the number.
public class Solution {
public int[] plusOne(int[] digits) {
boolean carry = false;
digits[digits.length-1]++;
for(int i=digits.length-1;i>=0;i--) {
if(carry) {
digits[i]++;
}
if(digits[i]==10) {
digits[i] = 0;
carry = true;
} else {
carry = false;
break;
}
}
if(!carry) {
return digits;
} else {
int ret[] = new int[digits.length+1];
ret[0] = 1;
for(int i=0;i<digits.length;i++) {
ret[i+1] = digits[i];
}
return ret;
}
}
}
没有评论:
发表评论