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.
Naive Way: 有没有可能面试官问这道题。
public class Solution {
public int[] plusOne(int[] digits) {
int[] rslt;
boolean carry = true;
for(int i = digits.length-1;i >=0;i--){
int v = digits[i]+(carry?1:0);
carry = v > 9;
v %= 10;
digits[i] = v;
}
if(carry){
rslt = new int[digits.length+1];
rslt[0] = 1;
for(int i = 1;i < rslt.length;i++) rslt[i] = digits[i-1];
}else{
rslt = digits;
}
return rslt;
}
}
No comments:
Post a Comment