您的位置:首页 > 其它

【leetcode】【66】Plus One

2015-06-11 12:37 477 查看
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;

    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: