【leetcode】【66】Plus One

来源:互联网 发布:74hc595数据手册 编辑:程序博客网 时间:2024/05/16 08:12

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.

解题思路:此题是把数组每个元素当成整数的一位,但是要考虑到第一个位置的进位问题,所以数组长度可能会增加,发现的问题:java中定义的数组不可变长,要想返回已经变长的,可以申请新的数组

public  static int[] plusOne(int[] digits) {
int tag=1;
int i;
        for(i=digits.length-1;i>=0;i--){
        digits[i]+=tag;
        if(digits[i]>=10){
        tag=1;
        digits[i]%=10;
        }else{
        break;
        }
        }
        if(tag==1&&i==-1){
        int [] str=new int[digits.length+1];
        for(int j=digits.length;j>0;j--){
        str[j]=digits[j-1];
        }
        str[0]=1;
        return str;
        }
        return digits;
    }

0 0
原创粉丝点击