標籤:
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.
解法1:將一個數位每個位上的數字分別存到一個一維向量中,最高位在最開頭。注意這是個大數問題,不能先遍曆以計算出digits所表示的數,然後再加1,最後將其順序放到vector中。
class Solution {public: vector<int> plusOne(vector<int>& digits) { vector<int> res; int n = digits.size(); int carry = 0; int one = 1; for(int i = n - 1; i >= 0; i--) { int num = digits[i] + one + carry; one = 0; carry = num / 10; res.push_back(num % 10); } if(carry) res.push_back(carry); reverse(res.begin(), res.end()); return res; }};
解法2:演算法如下:首先判斷最後一位是否為9,若不是,直接加一返回,若是,則該位賦0,再繼續查前一位,同樣的方法,知道查完第一位。如果第一位原本為9,加一後會產生新的一位,那麼最後要做的是,查運算完的第一位是否為0,如果是,則在最前頭加一個1。參考:http://www.cnblogs.com/grandyang/p/4079357.html
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] += 1; return digits; } } if (digits.front() == 0) digits.insert(digits.begin(), 1); return digits; }};
[LeetCode]11. Plus One加一運算