Plus One

easy 原题链接:https://leetcode.com/problems/plus-one/

Plus One

原题链接:https://leetcode.com/problems/plus-one/

描述

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.

解法一

deque

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;
	}
};

解法三

insert

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); 
        }
};

最后更新于

这有帮助吗?