-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddints.cpp
More file actions
87 lines (79 loc) · 1.83 KB
/
Addints.cpp
File metadata and controls
87 lines (79 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <iostream>
#include <vector>
using namespace std;
//todo: For a non-negative integer X, the array-form of X is an array of its digits in
// left to right order. For example, if X = 1231, then the array form is [1,2,3,1].
// Given the array-form A of a non-negative integer X, return the array-form of the
// integer X+K.
void addToArrayForm(vector<int> A, int K)
{
int s = A.size(), sum, carry = 0;
for (int i = 1; (K > 0) || (carry==1); i++)
{
if(i==s+1)
break;
sum = A[s - i] + (K % 10) + carry;
if (sum > 9)
{
sum %= 10;
carry = 1;
}
else
carry = 0;
A[s - i] = sum;
K /= 10;
}
if (carry == 1)
K++;
// A.insert(A.begin(), 1);
if(K>0)
{
while (K>0)
{
A.insert(A.begin(), (K%10));
K/=10;
}
}
cout << "Result: ";
for (int i = 0; i < A.size(); i++)
cout << A[i] << " ";
}
// todo: if K=1, same problem..
void addOne(vector<int>& digits)
{
int sum, s = digits.size(), carry=0, K=1;
for(int i=1; i<=s; i++)
{
sum = digits[s - i] + K + carry;
if (sum > 9)
{
sum %= 10;
carry = 1;
}
else
carry = 0;
digits[s - i] = sum;
K=0;
}
if (carry == 1)
digits.insert(digits.begin(), 1);
cout << "Result of AddOne: ";
for (int i = 0; i < digits.size(); i++)
cout << digits[i] << " ";
}
int main()
{
vector<int> v;
int val,k;
cout<<"Enter array: ";
for (int i = 0; i < 1; i++)
{
cin >> val;
v.push_back(val);
}
cout<<"Enter k: ";
cin>>k;
// addOne(v); // another function in which k+1
addToArrayForm(v, k);
}
// Q. 989. Add to Array-Form of Integer