[leetcode] 66. Plus One 解题报告

来源:互联网 发布:用文言文说网络流行语 编辑:程序博客网 时间:2024/06/02 03:54

题目链接:https://leetcode.com/problems/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.


思路:刚开始没怎么看懂题再见。其实就是一个元素表示整数的一位,然后在最左边加1,模拟进位,如果到最右边仍有进位,那就插入一个元素。

代码如下:

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        int flag =1;        for(auto it = digits.rbegin(); it != digits.rend(); it++)        {            int sum = *it + flag;            flag = sum/10;            *it = sum%10;        }        if(flag) digits.insert(digits.begin(), flag);        return digits;    }};



0 0