[LeetCode]66. Plus One

来源:互联网 发布:知乎 不能修改提问 编辑:程序博客网 时间:2024/06/04 18:28

题目描述:Given a non-negative number represented as an array of digits, plus one to the number.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
分析:用数组来表示一个数值(最高位在数组的0号索引位置,最低位在数组的长度减一的索引号上),将这个数值进行加1操作,并将得到的结果以数组的形式返回。

解题思路:模拟大数的加法运算

public int[] plusOne(int[] digits) {        int carry = 0;        int[] res = new int[digits.length+1];        int temp = digits[digits.length-1]+1;        for(int i=digits.length-1;i>=0;i--){            if(i!=digits.length-1)temp = digits[i]+carry;            if(temp>=10){                res[i]=temp%10;                carry = 1;            }else{                res[i]=temp;                carry = 0;            }        }        if(carry==1){            res[0]=1;            return res;        }else{            return Arrays.copyOfRange(res, 0, res.length-1);        }    }
原创粉丝点击