字母的编码问题,相同的编码如何用c语言去合并成数字呢

Problem Description
Given a string containing only 'A' - 'Z', we could encode it using the following method:

  1. Each sub-string containing k same characters should be encoded to "kX" where "X" is the only character in this sub-string.

  2. If the length of the sub-string is 1, '1' should be ignored.

Input
The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only 'A' - 'Z' and the length is less than 10000.

Output
For each test case, output the encoded string in a line.

Sample Input
2
ABC
ABBCCC

Sample Output
ABC
A2B3C

3个回答

直接+号应该就可以解决吧

shunfurh
编程介的小学生 不行
接近 2 年之前 回复

您好, 这个问题如果使用不同的思路去解决, 可以不用转换数字为字符串, 并且也不需要读取整行内容. 空间复杂度为 O(1).

#include <stdio.h>

int main() {
    int n;
    scanf("%d\n", &n);
    while (n--) {
        int count = 0, cur = getchar(), pre = cur;
        do {
            if (pre == cur) {
                ++count;
                continue;
            }
            else if (count == 1) 
                putchar(pre);
            else
                printf("%d%c", count, pre);
            if (cur == '\n') {
                putchar(cur);
                break;
            }
            pre = cur;
            count = 1;
        } while ((cur = getchar()) != EOF);
    }
}

如果您坚持要转换数字为字符串的话.
如果格式化的数字位数为1位, 可以用gann2010的回答的方法, 比如说将数字2变成字符'2', 2 + '0' 就得到 '2'. (需要掌握ascii编码规则)
更大的数可以使用sprintf/snprintf函数, 比如:

char buf[12];
int i = 1000;
sprintf(buf, "%d", i);

得到buf的内容为i的字符串形式. 即'1000'.

望采纳.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐