• + 0 comments

    c++ solution

    string encryption(string s) {
        int L = s.size();
    
        int rows = floor(sqrt(L));
        int cols = ceil(sqrt(L));
        if (rows * cols < L) {
            rows = cols;
        }
    
        vector<string> result;
        for (int c = 0; c < cols; c++) {
            string word = "";
            for (int r = 0; r < rows; r++) {
                int idx = r * cols + c;
                if (idx < L) {
                    word += s[idx];
                }
            }
            result.push_back(word);
        }
    
        string encoded = "";
        for (int i = 0; i < result.size(); i++) {
            if (i > 0) encoded += " ";
            encoded += result[i];
        }
    
        return encoded;
    }