您的位置:首页 > 其它

leetcode 66. Plus One

2017-08-19 15:39 519 查看
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list,the lowest digit is on the right end.
简单题一个。
public int[] plusOne(int[] digits) {
int add=1;
for(int i=digits.length-1;i>=0;i--){
if(digits[i]==9){
digits[i]=0;
}
else{
digits[i]+=1;
add=0;
break;
}
}
if(add==1){
int[] newDigits=new int[digits.length+1];
newDigits[0]=1;
for(int i=0;i<digits.length;i++){
newDigits[i+1]=digits[i];
}
return newDigits;
}
else{
return digits;
}
}这道题大神跟我解法一样,发现了我没想到的trick.
如果得到的 digits[0] 是 0 的话,那么所有的之后的元素肯定也是0,因此我们就没必要把 digits[] 来一一赋值给 res[i] ~ res[len+1] 。

public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >=0; i--) {
if (digits[i] != 9) {
digits[i]++;
break;
} else {
digits[i] = 0;
}
}
if (digits[0] == 0) {
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
return digits;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: