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,得到結果。跟Add Binary一樣,加上後進位。但容器的話,插入要用insert函數。
class Solution {public: vector<int> plusOne(vector<int> &digits) { int len = digits.size(); vector<int> res; if(len == 0){ res.push_back(1); return res; } int carry = 1; for(int i = len-1;i >= 0;i--){ int sum = digits[i]+carry; //先求總和再判斷是否進位 if(sum>=10) carry = 1; else carry = 0; res.insert(res.begin(),sum%10); //在容器的指定位置插入元素 } if(carry) res.insert(res.begin(),1); return res; }};
我是重新申請的一個來儲存新值,也可以在未經處理資料基礎上修改。
class Solution {public: vector<int> plusOne(vector<int> &digits) { int i; for(i = digits.size() - 1;i >= 0;--i){ if(digits[i] != 9){ ++digits[i]; return digits; } else { digits[i] = 0; } } //各位全是9 if(i < 0) { digits.insert(digits.begin(),1); } return digits; }};