首页 > 解决方案 > 计算C中一串数字中出现频率最高的数字

问题描述

我正在尝试计算字符串中最常见的数字,我需要使用指针,但我不确定如何使用指针来解决这个问题。

int most(char* string){
    int counter = 0;
    int* array =(int*) malloc(sizeof(int)*10);
    char* original = string;
    while(*original){
        counter++;
        string++;
        //Not sure what to put in this loop
    }
}

例如,我想调用代码

char nums[] = "132433423";
printf("%d \n",most(nums));
// 3

标签: cpointers

解决方案


您的功能规范不完整:

  • 字符串可以包含非数字字符吗?
  • 如果根本没有数字应该返回什么?
  • 如果有多个数字具有相同的最大出现次数,应该返回哪个值?
  • 该函数应该返回数字还是它的数值?您的main()函数使用后者,但从问题的文本中不清楚。

most函数接收一个指向字符串的指针。您可以编写一个循环,一次处理一个字符,并为下一次迭代递增指针,直到到达字符串的末尾。如果字符串不包含数字,您还必须决定返回什么。

这是一个简单的例子:

int most(const char *s) {
    int count[10] = { 0 };
    int res, i, max;

    while (*s) {
        if (*s >= '0' && *s <= '9')
            count[*s - '0']++;
        s++;
    }
    res = -1;  /* return -1 if no digits */
    max = 0;
    for (i = 0; i < 10; i++) {
        if (count[i] > max)
            res = i;
    }
    return res;
}

如果您完全不能使用任何数组,那么分配一块内存似乎确实是一个不错的解决方案:

int most(const char *s) {
    int *count = calloc(sizeof(*count), 10);
    int res, i, max;

    while (*s) {
        if (*s >= '0' && *s <= '9')
            *(count + *s - '0') += 1;
        s++;
    }
    res = -1;  /* return -1 if no digits */
    max = 0;
    for (i = 0; i < 10; i++) {
        if (*(count + i) > max)
            res = i;
    }
    free(count);
    return res;
}

该符号以*(count + *s - '0') += 1这种方式工作:是指向分配并初始化为bycount的数组的指针。是 所指向的字符的数字值 n ,已被测试为数字。是指向数组中第 n 个条目的指针。将此值加一。int0calloc*s - '0'scount + *s - '0'*(count + *s - '0') += 1

有一些方法可以在没有内存分配的情况下做到这一点,有 10 个变量和对不同数字的显式测试,但我怀疑这是预期的解决方案。

如果您可以向老师解释您的选择,有两种方法可以使用不带[and]字符的数组。这些是 C 标准的过时特性,大多数程序员都不熟悉,除非你好奇,否则可以忽略它们:

int most(const char *s) {  /* version with C99 digraphs */
    int count<:10:> = { 0 };
    int res, i, max;

    while (*s) {
        if (*s >= '0' && *s <= '9')
            count<:*s - '0':>++;
        s++;
    }
    res = -1;  /* return -1 if no digits */
    max = 0;
    for (i = 0; i < 10; i++) {
        if (count<:i:> > max)
            res = i;
    }
    return res;
}

或者

int most(const char *s) {  /* version with old-style trigraphs */
    int count??(10??) = { 0 };
    int res, i, max;

    while (*s) {
        if (*s >= '0' && *s <= '9')
            count??(*s - '0'??)++;
        s++;
    }
    res = -1;  /* return -1 if no digits */
    max = 0;
    for (i = 0; i < 10; i++) {
        if (count??(i??) > max)
            res = i;
    }
    return res;
}

推荐阅读