【Plus One】cpp
题目:
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.
代码:
class Solution { public: vector<int> plusOne(vector<int>& digits) { int carry = 1; for (std::vector<int>::reverse_iterator i = digits.rbegin(); i != digits.rend() && carry>0; ++i) { const int tmp = *i+carry; *i = tmp%10; carry = tmp/10; } if ( carry >0 ) digits.insert(digits.begin(), carry); return digits; } };
Tips:
高精度加法。
利用reverse_iterator来反向迭代vector。
========================================================
这种高精度的不要忘记最后一个的进位。
class Solution { public: vector<int> plusOne(vector<int>& digits) { vector<int> ret; int carry = 1; for ( int i=digits.size()-1; i>=0; --i ) { int curr = digits[i] + carry; carry = curr / 10; curr = curr % 10; ret.insert(ret.begin(), curr); } if ( carry!=0 ) ret.insert(ret.begin(), carry); return ret; } };