leetcode: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.

题意:一个非负整数按位存储于一个int数组中,排列顺序为:最高位在array[0] ,最低位在[n-1],例如:18,存储为:array[0]=1; array[1]=8;

思路:可以从数组的最后一位开始加1,注意需要考虑进位,如果到[0]位之后仍然有进位存在,则需要在数组起始处新开一个位来存储。

分析:从低位到高位,只有连续遇到9的情况最高位才能加1进位。所以代码如下:

class
Solution { public: vector<int> plusOne(vector<int>& digits) { int len = digits.size(); int i=0; for(i=len-1;i>=0;i--){ if(digits[i]<9){ digits[i]+=1; break;//只要最低位到最高位有一个低于9就不会产生[0]位之后的进位 } else { digits[i]=0; } }
//各位全是9时
if(i==-1){ digits.insert(digits.begin(), 1); } return digits; } };

其他解法:(非常容易理解)

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int i = digits.size() - 1;//相当于n=digits.size,i=n-1
        int carray = 1;
        while(i >= 0)
        {
            if(carray == 1)
            {
                int sum = digits[i] + 1;
                digits[i] = sum % 10;
                if(sum < 10)
                {
                    carray = 0;
                    break;
                }
            }
            i--;
        }

        if(carray == 1)
        {
            digits.insert(digits.begin(), 1);
        }

        return digits;
    }
};

  

posted @ 2015-06-06 19:23  小金乌会发光-Z&M  阅读(221)  评论(0编辑  收藏  举报