LeetCode066 Plus One

Given a non-empty array of digits representing a non-negative integer, increment one to the integer.

example:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

this problem is pretty straight forward.

class Solution {
    public int[] plusOne(int[] digits) {
        if (digits == null || digits.length == 0) {
            return null;
        }
        
        int i = digits.length - 1;
        while (i >= 0 && digits[i] == 9) {
            digits[i] = 0;
            i--;
            
        }
        if (i < 0) {
            int[] res = new int[digits.length + 1];
            Arrays.fill(res, 0);
            res[0] = 1;
            return res;
        } else {
            digits[i]++;
            return digits;
        }
        
    }
}

please also pay attention to the stupid answer given by myself 7 month ago

class Solution {
    public int[] plusOne(int[] digits) {
        boolean flag = false;
        for(int digit:digits){
            if(digit != 9){
                flag = true;
                break;
            }
        }
        if(flag == false){
            int[] temp = new int[digits.length + 1];
            temp[0] = 1;
            for(int i = 1;i<temp.length;i++){
                temp[i] = 0;
            }
            return temp;
        } else{
            int step = 1;
            for(int k = digits.length-1;k>=0;k--){
                if(digits[k] + step != 10){ //if not equal to 10, which means not need to step
                    digits[k] = digits[k]+step; //add step, if step =0 means no add, if step=1 means last 位have 进位
                    step = 0;//set step as 0;
                } else{
                    digits[k] = 0;
                    step = 1;
                }
            }
            return digits;
        }
    }
}
posted @ 2020-08-01 06:12  EvanMeetTheWorld  阅读(18)  评论(0)    收藏  举报