```
public class Solution {
public int MagicalString(int n) {
if (n == 0){
return 0;
}
StringBuilder temp = new StringBuilder("122");
int ones = 1;
for (int i = 2; temp.Length < n; i++){
int numToBeAdded = 1;
int countToBeAdded = temp[i] - '0';
if (temp[temp.Length - 1] == '1'){
numToBeAdded = 2;
}
if(numToBeAdded == 1){
ones++;
}
temp.Append(numToBeAdded);
if (temp.Length == n){
break;
}
if (countToBeAdded == 2){
temp.Append(numToBeAdded);
if(numToBeAdded == 1){
ones++;
}
}
}
return ones;
}
}
```