-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMagicalString.h
61 lines (54 loc) · 1.5 KB
/
MagicalString.h
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
//
// MagicalString.h
//
//
// https://leetcode.com/problems/magical-string/description/
//
#ifndef MagicalString_h
#define MagicalString_h
class Solution {
public:
int magicalString(int n) {
string upMagic = "";
string downMagic = "1";
int count = 0;
bool adding1 = true;
int iterator = 0;
while (true) {
if (iterator < upMagic.size()) {
downMagic += upMagic[iterator];
} else if (iterator == downMagic.size()) {
if (adding1) {
downMagic += '1';
} else {
downMagic += '2';
}
}
if (downMagic[iterator] == '1') {
if (adding1) {
upMagic += '1';
count += 1;
} else {
upMagic += '2';
}
adding1 = !adding1;
iterator++;
} else {
if (adding1) {
upMagic += "11";
count += 2;
} else {
upMagic += "22";
}
adding1 = !adding1;
iterator++;
}
if (upMagic.size() == n) {
return count;
} else if (upMagic.size() == n + 1) {
return upMagic.back() == '1' ? count - 1 : count;
}
}
}
};
#endif /* MagicalString_h */