66. Plus One

来源:互联网 发布:网络作家名字是字母的 编辑:程序博客网 时间:2024/05/22 15:02

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.


用vector数组存储一个数的每一位,要求对这个数加1,将这个数以同样的vector形式返回。先对第一位加1,如果有进位就继续对下一位加1,以此类推。这里最高位存在vector的首位,所以要倒过来遍历。如果计算完最后一位还有进位的,则在数组前插入1,。最后返回结果。


代码:

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        int n=digits.size();        int r=1,i=n-1;        while(r==1&&i>=0)        {            r=(digits[i]+1)/10;            digits[i]=(digits[i]+1)%10;            i--;        }        if(r==1)         {            digits.insert(digits.begin(),1);        }        return digits;    }};


0 0
原创粉丝点击