把 123456 做成214365,怎么写?

解决方案 »

  1.   

    CString str = "123456",strDest = "";
    for (int i = 0 ; i < str.GetLength() / 2; i++)
    {
         strDest += str[i * 2 + 1];
         strDest += str[i * 2];
    }
      

  2.   

    #include <iostream>
    #include <string>using namespace std;int main()
    {
        char buf[] = "123456";
        buf[0] ^= buf[1] ^= buf[0] ^= buf[1];
        buf[2] ^= buf[3] ^= buf[2] ^= buf[3];
        buf[4] ^= buf[5] ^= buf[4] ^= buf[5];
        cout << buf << endl;
        return 0;
    }
      

  3.   


    这种写法看起来很牛B:没有使用临时变量。
    其实,最好是使用:std::swap
      

  4.   

    int num=123456;
    char ch[6];
    _itoa(num,ch);
    ch[0]+=ch[1];
    ch[1]=ch[0]-ch[1];
    ch[0]-=ch[1];
    ch[2]+=ch[3];
    ch[3]=ch[2]-ch[3];
    ch[0]-=ch[1];
    har ch[6];
    _itoa(num,ch);
    ch[3]+=ch[2];
    ch[2]=ch[3]-ch[2];
    ch[3]-=ch[2];
    _atoi(ch,num);
      

  5.   

    没发好
    int num=123456;
    char ch[6];
    _itoa(num,ch);
    ch[0]+=ch[1];
    ch[1]=ch[0]-ch[1];
    ch[0]-=ch[1];
    ch[2]+=ch[3];
    ch[3]=ch[2]-ch[3];
    ch[2]-=ch[3];
    _atoi(ch,num);
      

  6.   

    改用循环:
    #include <iostream>
    #include <string>using namespace std;int main()
    {
        char buf[] = "123456";
        for (int i = 0; i < 6; i += 2)
            buf[i] ^= buf[i+1] ^= buf[i] ^= buf[i+1];
        cout << buf << endl;
        return 0;
    }
      

  7.   

    或者:
    #include <iostream>
    #include <string>using namespace std;int main()
    {
        char buf[] = "123456";
        for (int i = 0; i < 6; i += 2)
            buf[i] -= buf[i+1] = ((buf[i] += buf[i+1]) - buf[i+1]);
        cout << buf << endl;
        return 0;
    }