题目:
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.
提示:
此题其实是模拟我们在小学时候学习的加法进位的操作。难度不大。
代码:
空间复杂度是O(n)的方法:
class Solution { public: vector<int> plusOne(vector<int>& digits) { int size = digits.size() - 1; digits[size] += 1; if (digits[size] < 10) { return digits; } vector<int> result; for (int i = size; i > 0; --i) { if (digits[i] == 10) { digits[i] = 0; digits[i-1] += 1; } } if (digits[0] == 10) { result.push_back(1); digits[0] = 0; } for (int i = 0; i <= size; ++i) { result.push_back(digits[i]); } return result; } };
空间复杂度是O(1)的方法:
class Solution { public: vector<int> plusOne(vector<int>& digits) { for (int i = digits.size(); i--; digits[i] = 0) if (digits[i]++ < 9) return digits; digits[0] = 1; digits.push_back(0); return digits; } };