标签:style class blog code color 2014
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.
思路:原有数组需要多出一位的唯一条件是数组所有数值都为9,其他条件下只需要在原有数组下进行更改即可。
代码一:
class Solution { public: vector<int> plusOne(vector<int> &digits) { bool morePosition = true; for(int i = digits.size() - 1; i >= 0; i--) if(digits[i] != 9) { morePosition = false; break; } if(morePosition == false) { int carry = 0; if(digits[digits.size() - 1] + 1 == 10) { digits[digits.size() - 1] = 0; carry = 1; }else digits[digits.size() - 1]++; for(int i = digits.size() - 2; i >= 0 && carry == 1; i--) { if(digits[i] + carry == 10) { carry = 1; digits[i] = 0; }else { carry = 0; digits[i]++; } } } else { digits.push_back(0); for(int i = digits.size() - 2; i >= 1; i--) digits[i] = 0; digits[0] = 1; } return digits; } };
代码二更简洁,并且更有适应性。
class Solution { public: vector<int> plusOne(vector<int> &digits) { add(digits, 1); return digits; } private: // 0 <= digit <= 9 void add(vector<int> &digits, int digit) { int c = digit; // carry, 进位 for (auto it = digits.rbegin(); it != digits.rend(); ++it) { *it += c; c = *it / 10; *it %= 10; } if (c > 0) digits.insert(digits.begin(), 1); } };
【Leetcode】Plus One,布布扣,bubuko.com
标签:style class blog code color 2014
原文地址:http://blog.csdn.net/lipantechblog/article/details/30362729