# My accepted Java solution

• Just plus one to the last element in the digits , and judge every element then return

``````public class Solution {
public int[] plusOne(int[] digits) {
digits[digits.length-1]+=1;
for(int i=digits.length-1;i>0;i--)
{
if(digits[i]==10)
{
digits[i]=0;
digits[i-1]+=1;
}
}
if(digits[0]==10)
{
int[] res=new int[digits.length+1];
digits[0]=0;
res[0]=1;
for(int i=1;i<res.length;i++)
{
res[i]=digits[i-1];
}
return res;
}
return digits;
}
}``````

• kindly reference my solution

``````public class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
for ( int i = digits.length - 1; carry > 0 && i > -1; i-- ) {
int n = digits[i] + carry;
carry = n / 10;
digits[i] = n % 10;
}
if ( carry > 0 ) {
int[] n = new int[digits.length + 1];
n[0] = carry;
System.arraycopy(digits,0,n,1,digits.length);
digits = n;
}
return digits;
}
}``````

• ``````public int[] plusOne(int[] digits) {
if(digits.length < 1) return new int[]{1};
int flag = 1;
for(int i = digits.length -1; i >= 0; i--){
flag = digits[i] + 1;
if(flag > 9)
digits[i] = flag % 10;
else{
digits[i] = flag;
flag = 0;
break;
}
}
if(flag == 0)
return digits;
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}
``````

it can be a bit more simple.

• you didn't define the rest digits in res

• It's not required. The only time you need to allocate a new array is the case where digits was all 9s (otherwise, you're just going to return digits once you've modified it). In this case, the result is just 1000000...., where the size is one more than the size of digits. In Java, arrays are automatically filled with 0s, so we need only set the first digit to 1.

• You need not run complete for loop everytime. As soon as the loop encounters a digit[i-1] + 1 < 10 you can 'return digit'.

• You need not run complete for loop everytime. As soon as the loop encounters a digit[i-1] + 1 < 10 you can 'return digit'.

• Sure it is. Thanks for you improvement !

• good job! you can unstand me!

• see what krashman say. I just use the feature of jvm's initialization.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.