arrays - 有没有办法在这个 C 问题中使用数组?
问题描述
我正在做这个问题:
“我们有一个巨大的十进制数 N。编写一个程序来确定以下内容:
The number of digits in N.
Is N an even number?
The number of zeros in it.
Is N a multiple of 11? Note that we can determine if N is a multiple of 11 by checking the difference between the sum of the odd positioned digits and the sum of the even positioned digits. For example, 82375 is not a multiple of 11 because the sum of the even positioned digits is 2 + 7 = 9, and the sum of the odd positioned digits is 8 + 3 + 5 = 16, and the difference between 9 and 16 is 7, which is not a multiple of 11.
我们将为您提供每行的第一位数字。例如,如果你依次得到数字'1'、'2'、'3'、'4'、'0',则数字为12340。数字不会以0开头。 输入格式
输入有几行。每行都有一个数字。EOF 表示输入结束。输出格式
逐行输出上面的四个答案。如果数字是偶数,则输出 1;否则为 0。如果数字是 11 的倍数,则输出 1;否则输出 0。子任务
10 points: you can store the decimal number in an integer without overflow
10 points: the number of digits is no more than 32768, so you can store digits in an array
80 points: you will get MLE if you use array"
我的代码是:
#include <stdio.h>
#include <stdbool.h>
int digit(long n);
int is_even(int n);
int count_zeros(long n);
int is_multiple(long n);
int main() {
int digits = 0;
long x;
scanf("%ld", &x);
digit(x);
int even = is_even(x);
printf("%d\n", even);
printf("%ld\n",count_zeros(x));
printf("%ld\n", is_multiple(x));
}
int digit(long n)
{
int digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
printf("%ld\n", digits);
}
int is_even(int n)
{
if (n % 2 == 0)
return true;
else
return false;
}
int count_zeros(long n)
{
int count = 0;
while (n > 0) {
n /= 10;
if (n %10 == 0)
count++;
}
return count;
}
int is_multiple(long n)
{
if (n % 11 == 0) {
return true;
}
else
return false;
}
基本上我不知道如何满足问题的要求,所以我做了一个更简单的问题版本。关于如何做到这一点的任何线索?
如果您对此发表评论,请客气,我是初学者,过去人们很粗鲁,如果您没有什么要说的,请不要刻薄/不要发表评论。
解决方案
好吧,您当前版本的第一个问题是它只能读取一个整数。但是问题表明每个数字都在单独的行上。第一种方法可能只是用循环替换该 scanf 并保持乘以 10 并累积直到文件结束。然后程序的其余部分就可以正常工作了。
更高级的方法是使用数组来存储数字。一个整数可以容纳非常有限的位数,而使用数组的可用内存大小仅限于您。
因此,在读取循环中,您可以将数字存储在一个数组中,而不是将数字存储在一个整数中(它可以是固定大小,因为给出了上限)。但是对于程序的其余部分,您应该更改计算以使用数组中的数字而不是常规整数算术。
推荐阅读
- node.js - MongoDB:在路径中找不到标识符“elem”的数组过滤器
- microsoft-graph-api - 使用 Microsoft Graph API 加入 Skype 或 Teams 会议?
- python-3.x - 消息没有被刷新到 kafka
- git - 如果我有一个包含许多文件的大文件夹,如何创建不同的 github 存储库
- android - 如何将网页相关文件加载到android中的网页视图中?
- python - Python:将列表中的字符串相互连接
- javascript - 如何将异步功能与键值对 Google Chrome 扩展一起使用?
- python - 从 Python 列表中提取值
- python-3.x - 如何使用 python 在 Chromedriver 83 中启用 Flash
- linux - Linux - 共享互斥锁和 cond 变量的生命周期是什么