Cipher Discussions | Algorithms | HackerRank
  • + 0 comments
    string cipher(int k, string s) {
        int n = s.size();
        string res = "";
        res.push_back(s[0]);
        
        for(int i=1;i<n-k+1;i++){
            if(i < k){
                int x = (int)(s[i]-'0') ^ (int)(s[i-1]-'0');
                char ch = ('0'+x);
                res.push_back(ch);
            }
            else{
                int r = res.size();
                int x = 0;
                for(int j=r-1;j>=r-k+1;j--){
                    x ^= (int)(res[j]-'0');
                }
                x ^= (int)(s[i]-'0');
                char ch = (char)('0'+x);
                res.push_back(ch);
            }
        }
        return res;
    }