C++ solution


  • 0
    B

    but count and generate together

    int magicalString(int n) {
        int result=1;
        if(n<2)return n;
        int i=2,k;
        string str="122";
        while(str.length()<n)
        {
            for(k=0;k<str[i]-'0';k++)str+="1";
            result+=k;
            i++;
            for(k=0;k<str[i]-'0';k++)str+="2";
            i++;
        }
        for(k=str.length()-1;k>=n;k--)result-=(str[k]=='1');
        return result;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.