【问题标题】:(C Programming) How to find the most frequent occurring digit in long numbers without using array?(C编程)如何在不使用数组的情况下找到长数中出现频率最高的数字?
【发布时间】:2021-05-14 19:24:54
【问题描述】:

输入格式: 包含整数的单行。

约束: (-) 每个元素 = 0

输入样本: 3214144

输出格式: 包含出现频率最高的数字的单行。保证只有一个这样的数字。

输出样本: 4

这是我编写的代码:

int main(){
int input, i=0, num=0;
do{
    scanf("%i", &input);
    i=input%10;   
    break;
}while(input<= 9223372036854775807 && input>=0);
if (i+i==i*2){
    num+=1;
}
else{
    num=0;
}
if (num>0){
    printf("%i", i);
}
    return 0;
}

【问题讨论】:

  • 拜托我已经疯了一天了
  • 将数字转换为字符串,然后遍历字符串中的字符。
  • 您的代码在根本上没有意义。 break 立即退出循环,因此循环只运行一次迭代。为什么你还要在循环中使用scanf?您能否描述一下您尝试实现的算法,因为我真的无法从该代码中分辨出来?
  • 其实你应该把输入作为一个字符串..不要把它作为一个int读入。
  • 如果您不能使用数组,请制作 10 个变量 - 一个用于计算每个数字的计数。然后循环并根据变量之一更新它是什么数字。

标签: arrays c loops conditional-statements


【解决方案1】:

[asciitable][1] 中的字符可以被视为整数。字符“0”是数字 48。“9”是 48+9(即 57)。

'9' - '0' = 57 - 48 = 9。

将您读取的字符视为整数。制作一个数组来保存 10 个值。之后,数字最大的数字的索引就是你的解决方案。

#include <stdio.h>
int main() {
    char c;
    int counts[10] = {0,0,0,0,0,0,0,0,0,0};
    int max = 0;

    while(c=getc(stdin)){
        /* read until we get a newline */
        if (c=='\n') break;

        /* you can treat a char as an integer */
        counts[c-'0']++;
    }

    for(int i=0; i<10; i++) {
        if(counts[i] > counts[max]) max=i;
    }
    printf("%i is the max",max);


    return 0;
}

还要考虑 32 位 int 的最大值是 2147483647,而字符串可以是无限的。 [1]:https://www.asciitable.com

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多