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.
Solution:
public class Solution {
public int[] plusOne(int[] digits) {
boolean carry=true;
for(int i=digits.length-1;i>=0;i--)
{
if(digits[i]==9&&carry==true)
{
digits[i]=0;
if(i==0)//When all digits are 9, relocate a new array with length plus 1.
{
int[] newDigits=new int[digits.length+1];
for(int j=newDigits.length-1;j>0;j--)
newDigits[j]=digits[j-1];
newDigits[0]=1;
digits=newDigits;
break;
}
}
else if(carry==true)
{
digits[i]++;
carry=false;
}
}
return digits;
}
}
Discussion:Need to consider the extreme situation when the digits are all 9. Needs to relocate a new array with length plus 1. If the digit is 9, continues to carry 1 to the next digit. If not, stop carrying.
没有评论:
发表评论