Skip to content

Commit 32f4f40

Browse files
authored
Merge pull request #208 from abhisheks008/patch-1
Create ADD ONE TO NUMBER.CPP
2 parents 9e1c680 + 773103b commit 32f4f40

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

InterviewBit/ADD ONE TO NUMBER.CPP

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
vector<int> Solution::plusOne(vector<int> &A) {
2+
vector<int> result;
3+
if (A.empty())
4+
return result;
5+
6+
int z = 0; int size = A.size();
7+
while (z < size && A[z] == 0)
8+
++z;
9+
if (z == size)
10+
return vector<int> {1};
11+
12+
int carry = 0;
13+
for (int end = size-1; end>=z; --end)
14+
{
15+
if (end == size-1 && A[end] != 9)
16+
{
17+
++A[end];
18+
break;
19+
}
20+
21+
if (A[end] == 9)
22+
{
23+
A[end] = 0;
24+
carry = 1;
25+
}
26+
else
27+
{
28+
++A[end];
29+
carry = 0;
30+
break;
31+
}
32+
}
33+
34+
if (carry)
35+
{
36+
result.emplace_back(carry);
37+
vector<int> temp(A.cbegin() + z, A.cend());
38+
for (auto& t : temp)
39+
result.emplace_back(t);
40+
}
41+
else
42+
result = vector<int>(A.cbegin() + z, A.cend());
43+
return result;
44+
}

0 commit comments

Comments
 (0)