-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathsplit-array-into-fibonacci-sequence.cc
More file actions
44 lines (43 loc) · 1.01 KB
/
split-array-into-fibonacci-sequence.cc
File metadata and controls
44 lines (43 loc) · 1.01 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
// Split Array into Fibonacci Sequence
#define ALL(x) (x).begin(), (x).end()
#define ROF(i, a, b) for (remove_cv<remove_reference<decltype(b)>::type>::type i = (b); --i >= (a); )
class Solution {
public:
vector<int> splitIntoFibonacci(string S) {
int n = S.size();
long ta = 1, tb = 1;
long oa = 0, ob, oc, a, b, c;
vector<int> ret;
ROF(i, 0, n) {
oa += ta*(S[i]-'0');
ta *= 10;
if (oa > INT_MAX) break;
ob = 0;
tb = 1;
ROF(j, 0, i) {
ob += tb*(S[j]-'0');
tb *= 10;
if (ob > oa) break;
int k = j-1;
ret.clear();
ret.push_back(a = oa);
ret.push_back(b = ob);
while (k >= 0) {
c = a-b;
oc = c;
do if (S[k]-'0' != oc % 10) goto nxt;
while (k--, oc /= 10);
a = b;
b = c;
ret.push_back(c);
}
nxt:
if (k < 0 && ret.size() >= 3) {
reverse(ALL(ret));
return ret;
}
}
}
return {};
}
};