【leetcode】PlusOne
1,525 views
0
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
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-04-13 00:49:21
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!
转载注明: 【leetcode】PlusOne (米扑博客)