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

思路:

一开始没读懂题目o(╯□╰)o。试了一次题目的测试后才知道,一个个 digit 放进数组里,组成一个非负整数,然后加 1 求结果。

看懂题目后就很容易了,基本难点就是操作进位,特别是在最高位需要插入时,可能会造成一些 iterator 的 incompatible 错误或是 not decrementable 的错误,前者可能是因为 vector 容器内存重新分配造成的,经过一些插入或删除的操作后再使用之前在用的迭代器,很可能出错;后者可能是因为已经来到容器头部或尾部而继续往下操作出现错误。

代码:

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        vector<int>::reverse_iterator rit = digits.rbegin();
        *rit += 1;
        for (; rit != digits.rend(); rit++)
        {
            if (*rit > 9)
            {
                int temp = *rit;
                *rit = temp % 10;
                if (rit + 1 != digits.rend())
                {
                    *(rit + 1) += 1;
                }
                else
                {
                    digits.insert(digits.begin(), 1);
                    break;
                }
            }
        }
        return digits;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值