LeetCode 066 Plus One

来源:互联网 发布:魔域单机版源码 编辑:程序博客网 时间:2024/06/10 04:37
题目


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.

对于数组代表的数,进行加1计算,返回数组


思路


1 这道题目我个人认为不太好,实际当中返回数组什么的有点奇怪;而且数组固定大小,还要进行调整。

2 当然这道题目考的就是有没有注意到数组有可能变长,并且如何调整。原数组肯定都是正好一位对一位,最后返回的时候,也必须是一位对一位,不能开头有多余的0

3 这样,我的思路是,直接开一个多一位的数组来进行计算。如果不需要的话,那么最后把开头的那位去除的数组返回即可。

4 当心写成每一位都加一。


代码


public class Solution {    public int[] plusOne(int[] digits) {        if(digits.length==0){            return digits;        }        int n = digits.length;        int[] ans = new int[n+1];        int c = 1;        for(int i =n-1;i>=0;i--){            ans[i+1]=(c+digits[i])%10;            c = (c+digits[i])/10;        }        if(c==1){            ans[0]=1;            return ans;        }        else{            for(int i=0;i<n;i++){                digits[i]=ans[i+1];            }            return digits;        }            }}



0 0
原创粉丝点击