Question:

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.

Answer:

public class Solution {
    public int[] plusOne(int[] digits) {
        int len=digits.length;
        int index=-1;
       for(int i=len-1;i>=0;i--){
           if(digits[i]!=9){
               index=i;
               break;
           }
       }
     if(index==-1){
             int[] res=new int[digits.length+1];
            res[0]=1;
            return res;
       }
       digits[index]++;
       for(int j=index+1;j<len;j++){
           digits[j]=0;
       }
    
           return digits;
       
    }
}

OR

public int[] plusOne(int[] digits) {
    int carry = 1;
    for (int i = digits.length-1; i>= 0; i--) {
        digits[i] += carry;
        if (digits[i] <= 9) // early return 
            return digits;
        digits[i] = 0;
    }
    int[] ret = new int[digits.length+1];
    ret[0] = 1;
    return ret;
}

相关文章:

  • 2021-10-17
  • 2021-11-28
  • 2021-05-30
猜你喜欢
  • 2021-07-06
  • 2021-10-26
  • 2021-07-23
  • 2021-12-22
相关资源
相似解决方案