Question:
Given a number represented as an array of digits, plus one to the number.
Anwser 1: szie -> 0
class Solution { public: vector<int> plusOne(vector<int> &digits) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> result(digits); int carry = 1; int size = digits.size(); for(int i = size - 1; i >= 0 ; i--){ int tmp = result[i] + carry; result[i] = tmp % 10; carry = tmp / 10; } if(carry > 0){ result.insert(result.begin(), carry); } return result; } };
Anwser 2: 0 -> szie
class Solution { public: vector<int> plusOne(vector<int> &digits) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> result(digits); reverse(result.begin(), result.end()); int carry = 1; int size = digits.size(); for(int i = 0; i < size; i++){ int tmp = result[i] + carry; result[i] = tmp % 10; carry = tmp / 10; } if(carry == 1){ result.push_back(carry); } reverse(result.begin(), result.end()); return result; } };
参考推荐:
leetcode.com