LeetCode 066. Plus One

来源:互联网 发布:网络水军如何找站 编辑:程序博客网 时间:2024/06/06 02:46
66. Plus One

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.
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
    }
};
解题思路:
  • 自己的解题思路
从低位依次增加1,考虑进位的影响。对于999这样的输入,会对size产生影响,因此我用了一个resize()进行处理。但是,这个处理方法,浪费了之前已经将其他位置为0的处理结果,因此还有更简单的方法。
  • 别人的解题思路
只要不是9进行加位,就可以提前退出。思路很简单,程序很巧妙,很美观。
学习收获:
  • 第一次写程序的时候,没有注意carry的复位情况。导致,WA
  • 对于测试用例的探讨。
这题没有考虑测试用例为空的情况。个人觉得需要考虑进去。还有就是测试用例为负数的情况。虽然,题目已经说了是非负数。但是,我们可以自己造轮子。如果改一下,digits[0]可能为负数,这样的话,题目需要考虑的因素就更多。
附件:程序
1、自己的程序:
classSolution
{
    public:
    vector<int>plusOne(vector<int>&digits)
    {
        if(!digits.size())
        {
            return{};
        }
        if(digits[0]<0){return{};}
        intcarry=0;
        inti=digits.size()-1;
        ++digits[i];
        if(digits[i]==10)
        {
            digits[i]=0;
            carry=1;
        }
        for(--i;i>=0;--i)
        {
            digits[i]+=carry;
            if(digits[i]==10)
            {
                digits[i]=0;
                carry=1;
            }
            //at the beginning, I forgot to reset the carry
            else
            {
                carry=0;
            }
        }
        //a better one
    /*  if(1 == carry)
        {
            ++digits[0];
            digits.push_back(0);
        }*/
        if(1==carry)
        {
            autolen=digits.size();
            digits.clear();
            digits.resize(len+1,0);
            digits[0]=1;
        }
        returndigits;
    }
};
2、别人的程序
如果digits为空的话,这个程序有问题。但是,这种情况却没有考虑进去。所以,有时候测试用例真是个情况的东西,很难琢磨清楚。
vector<int>plusOne(vector<int>&digits)
{
    for(inti=digits.size();i--;digits[i]=0)
        if(digits[i]++<9)
            returndigits;
    ++digits[0];
    digits.push_back(0);
    returndigits;
}
没有使用carry
classSolution
{
    public:
    vector<int>plusOne(vector<int>&digits)
    {
        for(inti=digits.size()-1;i>=0;i--)
        {
            digits[i]++;
            if(digits[i]<10)
                break;
            digits[i]=0;
        }
        if(digits[0]==0)
        {
            digits[0]=1;
            digits.push_back(0);
        }
        returndigits;
    }
};
0 0
原创粉丝点击