LeetCode -- 66. Plus One

来源:互联网 发布:帝国时代2知乎 编辑:程序博客网 时间:2024/05/20 05:26

题目:

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.


思路:
这道题比较简单,主要考察vector的基本操作。从vector的最后一位进行判断,是9则进位,否则直接+1返回。如果跳出了循环,则表明最高位被置0了,此时,只需要把最高位改成1,在最低位添加一个0即可。


C++代码如下:

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