My accepted Java solution


  • 6
    A

    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;
        }
    }

  • 4
    R

    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;
        }
    }

  • 1
    F
    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.


  • 0
    L

    you didn't define the rest digits in res


  • 0
    K

    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.


  • 0
    R

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


  • 0
    R

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


  • 0
    A

    Sure it is. Thanks for you improvement !


  • 0
    F

    good job! you can unstand me!


  • 0
    F

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


Log in to reply
 

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