66. Plus One

来源:互联网 发布:cura切片生成软件 编辑:程序博客网 时间:2024/06/05 00:57

1.Question

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.

2.Code

CodeA

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        for(vector<int>::reverse_iterator it = digits.rbegin(); it != digits.rend(); it++)        {            if(*it != 9)    {(*it)++; break;}            else    *it = 0;        }        if(digits[0] == 0) digits.insert(digits.begin(), 1);        return digits;    }};

CodeB

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        for(int i = digits.size() - 1; i >= 0; i--)        {            if(digits[i] != 9)    {(digits[i])++; break;}            else    digits[i] = 0;        }        if(digits[0] == 0) digits.insert(digits.begin(), 1);        return digits;    }};

3.Note

a. CodeA 里用到迭代器去循环,遍历,而且是倒序遍历。注意是it++而不是it--。 CodeB则直接用数字来做标记。

0 0
原创粉丝点击