题目:
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。
时间: 2024-10-18 01:45:40