21.Plus One

来源:互联网 发布:按option无法切换mac 编辑:程序博客网 时间:2024/06/08 04:35

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.

分析:首先判断所有的是否都为数字9,是的话则数组长度加1,首位为1,其他位是0;否则,从最低位开始加1,知道遇到某位的数字小于9结束。

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


0 0
原创粉丝点击