C语言中计算N次移动后数组中1的个数
给定一个大小为N的数组,数组初始值全为0。任务是在N次移动后计算数组中1的个数。每次移动都关联一个规则:
第一次移动 - 改变位置1, 2, 3, 4……的元素
第二次移动 - 改变位置2, 4, 6, 8……的元素
第三次移动 - 改变位置3, 6, 9, 12……的元素
计算最终数组中1的个数。
让我们通过例子来理解。
输入
Arr[]={ 0,0,0,0 } N=4输出
Number of 1s in the array after N moves − 2
解释 - 按照以下步骤移动后的数组:
Move 1: { 1,1,1,1 }
Move 2: { 1,0,1,0 }
Move 3: { 1,0,0,3 }
Move 4: { 1,0,0,1 }
Number of ones in the final array is 2.输入
Arr[]={ 0,0,0,0,0,0} N=6输出
Number of 1s in the array after N moves − 2
解释 - 按照以下步骤移动后的数组:
Move 1: { 1,1,1,1,1,1,1 }
Move 2: { 1,0,1,0,1,0,1 }
Move 3: { 1,0,0,1,0,0,1 }
Move 4: { 1,0,0,0,1,0,0 }
Move 5: { 1,0,0,0,0,1,0 }
Move 4: { 1,0,0,0,0,0,1 }
Number of ones in the final array is 2.下面程序中使用的方案如下:
我们使用一个初始化为0的整数数组Arr[]和一个整数N。
函数Onecount接收Arr[]及其大小N作为输入,并返回N次移动后最终数组中1的个数。
for循环从1开始到数组末尾。
每个i代表第i次移动。
嵌套for循环从第0个索引开始到数组末尾。
对于每次第i次移动,如果索引j是i的倍数(j%i==0),则将该位置的0替换为1。
这个过程对每个i持续到数组末尾。
注意 - 索引从i=1,j=1开始,但数组索引是从0到N-1。因此,arr[j-1]每次都会被转换。
最后再次遍历整个数组,计算其中1的个数并存储在count中。
- 返回count作为期望结果。
示例
#include <stdio.h>
int Onecount(int arr[], int N){
for (int i = 1; i <= N; i++) {
for (int j = i; j <= N; j++) {
// If j is divisible by i
if (j % i == 0) {
if (arr[j - 1] == 0)
arr[j - 1] = 1; // Convert 0 to 1
else
arr[j - 1] = 0; // Convert 1 to 0
}
}
}
int count = 0;
for (int i = 0; i < N; i++)
if (arr[i] == 1)
count++; // count number of 1's
return count;
}
int main(){
int size = 6;
int Arr[6] = { 0 };
printf("Number of 1s in the array after N moves: %d", Onecount(Arr, size));
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Number of 1s in the array after N moves: 2
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP