HDU2562 奇偶位互换【输入输出流】

奇偶位互换

Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7881    Accepted Submission(s): 5928

Problem Description
给定一个长度为偶数位的0,1字符串,请编程实现串的奇偶位互换。
Input
输入包含多组测试数据;
输入的第一行是一个整数C,表示有C测试数据;
接下来是C组测试数据,每组数据输入均为0,1字符串,保证串长为偶数位(串长<=50)。
Output
请为每组测试数据输出奇偶位互换后的结果;
每组输出占一行。
Sample Input
2 0110 1100
Sample Output
1001 1100
Author
yifenfei
Source

问题链接HDU2562 奇偶位互换

问题简述参见上文。

问题分析:(略)

程序说明

这里给出了两个程序,一个使用了数组,另外一个则仅仅使用字符流。明显,仅仅使用字符流是正解。

函数swap是C语言程序的套路,如果是C++语言程序则可以直接用该函数。

题记

函数get()已经不被推荐使用,用函数fgets()吧!

存储要能省则省!


参考链接:(略)


AC的C语言程序如下:

/* HDU2562 奇偶位互换 */

#include <stdio.h>

int main(void)
{
    int c, ch1, ch2;

    scanf("%d", &c);
    getchar();
    while(c--) {
        for(;;) {
            if((ch1 = getchar()) == '
') {
                putchar('
');
                break;
            }
            ch2 = getchar();

            putchar(ch2);
            putchar(ch1);
        }
    }

    return 0;
}

AC的C语言程序如下:

/* HDU2562 奇偶位互换 */

#include <stdio.h>

#define N 50

char s[N+2];

void swap(char *a, char *b)
{
    char t = *a;
    *a = *b;
    *b = t;
}

int main(void)
{
    int c, i;

    scanf("%d", &c);
    getchar();
    while(c--) {
        fgets(s, N, stdin);

        i = 0;
        while(s[i] != '
') {
            swap(&s[i], &s[i+1]);
            i += 2;
        }
        s[i] = '';

         printf("%s
", s);
    }

    return 0;
}




原文地址:https://www.cnblogs.com/tigerisland/p/7563587.html