LeetCode 66.Plus One

来源:互联网 发布:firefox知乎 编辑:程序博客网 时间:2024/06/12 19:13

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

题解:

题目意思就是对非零数字进行加1操作,然后把结果返回即可,实现方法为利用反向迭代器从后向前进行加1操作,记录进位标志,最后再判断进位是否存在,即进位是不是一个非零数

vector<int> plusOne(vector<int>& digits) {        int sign = 1;        for (auto i = digits.rbegin(); i != digits.rend(); i++){            *i += sign;            sign = *i / 10;            *i %= 10;        }        if (sign > 0){            digits.insert(digits.begin(),1);        }        return digits;    }


原创粉丝点击