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] 。
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; }
相关文章推荐
- LeetCode_66. Plus One_数组加一
- Java [Leetcode 66]Plus One
- LeetCode 66 Plus One(加一)(vector)
- 【一天一道LeetCode】#66. Plus One
- Leetcode 66 Plus One
- leetcode 21_Merge Two Sorted Lists & leetcode_258 Add Digits & leetcode_66plus one
- LeetCode】66.Plus One(easy)解题报告
- leetcode 66:Plus One
- Plus One - LeetCode 66
- 个人记录-LeetCode 66. Plus One
- [Leetcode 4] 66 Plus One
- [LeetCode 66] Plus One
- LeetCode66. Plus One-python(easy)
- 【Leetcode】66. Plus One
- leetcode ||66、 Plus One
- [LeetCode]66. Plus One
- leetcode 66. Plus One
- LeetCode 66. Plus One
- leetCode 66. Plus One 数组
- Leetcode_66_Plus One