Plus One Solutions in C++
Number 66
Difficulty Easy
Acceptance 43.0%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/plus-one/// Author : Hao Chen// Date : 2014-06-21#include <iostream>#include <vector>using namespace std;vector<int> plusOne(vector<int> &digits) {int carry=1;vector <int> v;while(digits.size()>0){int x = digits.back();digits.pop_back();x = x + carry;v.insert(v.begin(), x%10);carry = x/10;}if (carry>0){v.insert(v.begin(), carry);}return v;}void printVector(vector<int>& v){cout << "{ ";for(int i=0; i<v.size(); i++){cout << v[i] << " ";}cout << "} " << endl;}int main(){int a[]={9,9,9};vector<int> d(&a[0], &a[0]+sizeof(a)/sizeof(int));vector<int> v = plusOne(d);printVector(v);return 0;}
C++ solution by pezy/LeetCode
#include <vector>using std::vector;class Solution {public:vector<int> plusOne(vector<int> &digits) {for (auto iter = digits.rbegin(); iter != digits.rend(); ++iter)if (++*iter < 10) break;else *iter = 0;if (digits.front() == 0) digits.insert(digits.begin(), 1);return digits;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/plus-one/description//// Author : liuyubobobo/// Time : 2018-06-03#include <iostream>#include <vector>using namespace std;/// Ad Hoc/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<int> plusOne(vector<int>& digits) {digits[digits.size() - 1] ++;for(int i = digits.size() - 1 ; i >= 1 ; i --)if(digits[i] == 10){digits[i] = 0;digits[i - 1] ++;}if(digits[0] == 10){digits[0] = 0;digits.insert(digits.begin(), 1);}return digits;}};int main() {return 0;}