Leecode 关于异或的题

Posted shinered

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leecode 关于异或的题相关的知识,希望对你有一定的参考价值。

每条信息被编译为二进制数B,其长度为N然后该信息被写下N次,每次向右移动0,1,...K-1位。 

如 B = 1001010, K= 4

1001010

 1001010

   1001010

     1001010

这样的结果是1110100110 (S),要求实现解密过程。 

解题思路: 当数组B长度大于等于3时,S的对应位置应该是由B本位的前3位异或计算组成的。

#include <iostream>
#include <vector>
#include <string>
using namespace std;


int cal_xor(vector<int> &a) 
    int _xor = a[a.size()-1] ^ a[a.size()-2];
    cout << "a.size()-4:" << a.size()-1 << endl;
    cout << a[a.size()-1] << a[a.size()-2]  << a[a.size()-3] << ,;
     int j = a.size()-2;
    cout << "a.size()-3:" << a.size()-4 << endl;
/*    for(; j >= a.size()-3; j--)
        cout << j << ",";
//        cout << a[j] << ",";
    */
    /*for(unsigned int i = a.size()-2;i > a.size()-4; i--) 
    
    cout << i << ",";
        cout << a[i] << ",";
        _xor = _xor^a[i];
    */
    _xor = _xor ^ a[a.size()-3];
    cout << "xor()" << _xor << endl;
    return _xor;

int main()

int N, K;
    cin >> N;
    cin >> K;
    string s;
    cin >> s;
    vector<int>s2;
    cout << "N:" << N << ",K:" << K << endl;
    cout << "s:" << s << endl;
    s2.push_back(s[s.size()-1]-0);
    cout << s2[0] << endl;
    int _xor = s2[0];
    for (int i = s.size()-2; i > 0; i--)    
        
        //_xor = (s[i]-‘0‘) ^ _xor;
    //    if(_xor == 0) 
    //        s2.push_back()
    //    
        cout << s2.size() << "xor:" <<  _xor << endl;
        if(s[i]-0 ==0) 
            cout <<"s[i]" << s[i] << endl;
            s2.push_back(_xor);
         else 
            cout <<"s[i]" << s[i] << endl;
            if(_xor ==0) 
            s2.push_back(1);
             else
                s2.push_back(0);
            
        

        cout << "s2:" << s2.size()     << endl;
        if(s2.size()>=3)
            cout << "s2.size(): " << s2.size() <<endl;;
            for(int k = 0; k < s2.size(); k++) 
                cout << s2[k] << "," << endl;
            
            _xor = cal_xor(s2);
         else 
            _xor = _xor^(s2[s2.size()-1]);
        

        if(s2.size()==N) 
            break;
        
    
    vector<int> result;
            for(int i = s2.size()-1; i >=0; i--) 
                //cout << s2[i] << ",";
                result.push_back(s2[i]);
                cout << s2[i] << ",";
            

 

以上是关于Leecode 关于异或的题的主要内容,如果未能解决你的问题,请参考以下文章

leecode-268. 丢失的数字(异或的应用,找没有出现的数字,找只出现一次的数字)

leecode-268. 丢失的数字(异或的应用,找没有出现的数字,找只出现一次的数字)

leecode第二天-使用异或找出数组中的非重复元素

Leecode位运算与堆排序

leecode 278 数值溢出感想

关于排序的相关代码(数据结构笔试复测Leecode牛客)