求一批整数中出现最多的数字。输入一个正整数 n (1<n≤1000),再输入 n 个整数,分析 每个整数的每一位数字,求出现次数最多的各位数字。例如输入 3 个整数 1234、2345、3456, 其中出现次数最多的数字是 3 和 4,均出现了 3 次。试编写相应程序。
时间: 2023-04-14 10:02:58 浏览: 840
首先,我们需要遍历每个整数的每一位数字,统计每个数字出现的次数。可以使用一个长度为 10 的数组来记录每个数字出现的次数,数组下标表示数字,数组值表示出现次数。遍历完所有整数后,再遍历一次数组,找出出现次数最多的数字即可。
以下是示例代码:
n = int(input("请输入整数个数:"))
nums = []
for i in range(n):
num = int(input("请输入第%d个整数:" % (i+1)))
nums.append(num)
count = [] * 10 # 初始化每个数字出现次数为
for num in nums:
while num > :
digit = num % 10 # 取出最低位数字
count[digit] += 1 # 对应数字出现次数加 1
num //= 10 # 去掉最低位数字
max_count = max(count) # 找出出现次数最多的数字出现次数
max_digits = [] # 记录出现次数最多的数字
for i in range(10):
if count[i] == max_count:
max_digits.append(i)
print("出现次数最多的数字是:", end="")
for digit in max_digits:
print(digit, end=" ")
相关问题
求一批整数中出现最多的数字。输入一个正整数n(1<n≤1000),再输入n个整数,分析每个整数的每一位数字,求出现次数最多的数字。
以下是Python实现求一批整数中出现最多的数字的代码:
```python
n = int(input("请输入正整数n:"))
nums = input("请输入n个整数,用空格隔开:").split()
# 统计每个数字出现的次数
count = {}
for num in nums:
for digit in num:
if digit in count:
count[digit] += 1
else:
count[digit] = 1
# 找出出现次数最多的数字
max_count = 0
max_digit = ''
for digit, c in count.items():
if c > max_count:
max_count = c
max_digit = digit
print("出现次数最多的数字是:", max_digit)
```
输入样例:
```
请输入正整数n:5
请输入n个整数,用空格隔开:123 456 789 12345 67890
```
输出样例:
```
出现次数最多的数字是:3
```
求一批整数中出现最多的数字。输入一个正整数n(1<n≤1000),再输入n个整数,分析 每个整数的每一位数字,求出现次数最多的各位数字c语言。
以下是C语言实现求一批整数中出现最多的数字的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, num, max_num = 0, max_count = 0;
int count[10] = {0}; // 数字0~9出现的次数
printf("请输入正整数n:");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("请输入第%d个整数:", i + 1);
scanf("%d", &num);
while (num > 0) {
int digit = num % 10;
count[digit]++;
num /= 10;
}
}
for (int i = 0; i < 10; i++) {
if (count[i] > max_count) {
max_count = count[i];
max_num = i;
}
}
printf("出现次数最多的数字是:%d,出现了%d次。\n", max_num, max_count);
return 0;
}
```
阅读全文