Easy
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.
1ms:
public int[] plusOne(int[] digits) {
boolean b = false;
for(int i=digits.length-1;i>=0;i--){
if(digits[i]==9){
digits[i] = 0;
b = true;
continue;
}else{
digits[i]++;
b = false;
break;
}
}
if(b){
int[] bd = new int[digits.length+1];
for(int j=digits.length;j>0;j--){
bd[j] = digits[j-1];
}
bd[0] = 1;
digits = bd;
}
return digits;
}
本文介绍了一种在数字以数组形式存储的情况下,对该数字加一的高效算法实现。该算法从数组末尾开始检查每一位是否为9,并进行相应的进位处理。如果最高位产生进位,则会在数组前增加一位。
593

被折叠的 条评论
为什么被折叠?



