c++奇偶数位分别逆序输出

从键盘输入一个正整数,奇数位逆序构成一个新数赋值给a,偶数位逆序构成一个新数赋值给b,奇偶位按照原数据从高位到低位顺序确定,在屏幕上分别输出a和b,中间用空格分隔。
测试: 123456789000123456000 
输出:531097531 642008642

img

代码如下:


#include <iostream>
using namespace std;
#define MAXLEN (int)100
int main()
{
    char str[MAXLEN];
    char a[MAXLEN], b[MAXLEN];
    int lena = 0, lenb = 0;
    int flag = 0;
    cin >> str; //读入正整数(已字符串形式读入)
    for (int i = 0; str[i] != '\0'; i++)
    {
        if (i % 2 == 1)
            b[lenb++] = str[i];
        else
            a[lena++] = str[i];
    }
    //逆序输出
    //输出a
    lenb--;
    lena--;
    for (; lena >= 0; lena--)
    {
        if (a[lena] != '0')
            flag = 1;
        if (flag == 1)
            cout << (char)a[lena];
    }
    cout << " ";
    //输出b
    flag = 0;
    for (; lenb >= 0; lenb--)
    {
        if (b[lenb] != '0')
            flag = 1;
        if (flag == 1)
            cout << (char)b[lenb];
    }
    return 0;
}

img

你题目的解答代码如下:

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[100], a[100], b[100];
    int len, i, alen = 0, blen = 0;
    cin >> str;
    len = strlen(str);
    for (i = len - 1; i >= 0; i--)
    {
        if (i % 2 == 0)
        {
            if (str[i] != '0' || alen > 0)
                a[alen++] = str[i];
        }
        else
        {
            if (str[i] != '0' || blen > 0)
                b[blen++] = str[i];
        }
    }
    a[alen] = '\0';
    b[blen] = '\0';
    cout << a << " " << b;
    return 0;
}

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img


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

int main() {
    string str,a="",b="";
    cin >> str;
    
    for(int i=0;i<str.size();i++)
    {
        if(i%2==0)
        {
            b+=str[i];
        }else
            a+=str[i];
    }
    reverse(a.begin(), a.end());
    reverse(b.begin(), b.end());
    cout << atoi(a.c_str()) << " " <<atoi(b.c_str()) << endl;

    return 0;
}