```
class MagicalStringSolution {
public int magicalString(int n) {
if (n <= 0) return 0;
if (n == 1 || n == 2) return 1;
int sum = 1;
StringBuilder s1 = new StringBuilder("12");
int index = 1;
int count = 1;
char curr = '2';
while (index < n) {
if (s1.charAt(index) == '1') sum++;
while (count < s1.charAt(index) - '0') {
s1.append(curr);
count++;
}
count = 0;
if (curr == '1') curr = '2';
else curr = '1';
index++;
}
return sum;
}
}
```