Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
deque<int> dig;
dig.assign(digits.begin(),digits.end());
for (int i = n - 1; i >= 0; --i)
{
if (dig[i] == 9)
{
dig[i] = 0;
if(i==0){
dig.push_front(1);
}
}else{
dig[i]++;
break;
}
}
vector<int>res;
res.assign(dig.begin(),dig.end());
return res;
}
};
class Solution {
public:
vector<int>plusOne(vector<int> &digits)
{
int n = digits.size();
for (int i = n - 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;
}
};
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
add(digits, 1);
return digits;
}
private:
// 0 <= digit <= 9
void add(vector<int> &digits, int digit) {
int c = digit; // carry,
for (auto it = digits.rbegin(); it != digits.rend(); ++it) {
*it += c;
c = *it / 10;
*it %= 10;
}
if (c > 0) digits.insert(digits.begin(), 1);
}
};