描述:给定一个非负数,表示一个数字数组,在该数的基础上+1,返回一个新的数组。 该数字按照大小进行排列,最大的数在列表的最前面。 样例 给定 [1,2,3] 表示 123, 返回 [1,2,4]. 给定 [9,9,9] 表示 999, 返回 [1,0,0,0].
新知识点: vector<int> c; c.begin() 返回一个迭代器,它指向容器c的第一个元素
c.end() 返回一个迭代器,它指向容器c的最后一个元素的下一个位置
c.rbegin() 返回一个逆序迭代器,它指向容器c的最后一个元素
c.rend() 返回一个逆序迭代器,它指向容器c的第一个元素前面的位置
以上四个函数返回的都是地址,要取指向的元素应该加上*。 容器名.insert(位置,元素)举例:
c.insert(c.begin(),8);//在最前面插入新元素8。 c.insert(c.begin()+2,1);//在迭代器中第二个元素前插入新元素1 c.insert(c.end(),3);//在向量末尾追加新元素3。思路:从末尾开始加1操作,然后余数放在原位置,商和原末尾数第二个位置的数之和放在第二个位置,以此类推。最后判断商是不是大于0,如果是,就增加一个最高位写1.
class Solution { public: /* * @param digits: a number represented as an array of digits * @return: the result */ vector<int> plusOne(vector<int> digits) { // write your code here add(digits, 1); return digits; } private: void add(vector<int> &digits, int res){ for (auto it = digits.rbegin(); it != digits.rend(); ++ it) {//从末尾地址开始,地址逐次加1,直到地址指向首地址 *it += res; res = *it / 10; *it %= 10; } if (res > 0) digits.insert(digits.begin(), 1);//当最后商还大于0,说明还有其和是超过10,应该进位 } };