clueless coding // TODO: be smarter

LeetCode Magical String: CPP Solution



TL;DR Code Solution


int magicalString(int n) {

    if (n == 0) {
        return 0;
    }

    if (n <= 3) {
        return 1;
    }

    string s = "122";

    int occurences = 2;
    int end = 2;

    while (end <= n) {

        for (int i = 0; i < s[occurences] - '0'; i++) {
            if (s[end] == '2') {
                s += '1';
            }
            else {
                s += '2';
            }
        }

        end += s[occurences] - '0';
        occurences++;
    }



    int count = 0;
    for (int i = 0; i < n; i++) {
        if (s[i] == '1') {
            count++;
        }
    }

    cout << s;
    return count;

}