给定一个大小为 N 的数组。该数组最初全为 0。任务是数数。 N 次移动后数组中 1 的个数。每个第 N 步都有一个关联的规则。规则是 -
第一次移动 - 更改位置 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 和整数 N 初始化的整数数组 Arr[]。
函数 Onecount 将 Arr[] 及其大小 N 作为输入并返回 no。 N 次移动后最终数组中的个数。
for 循环从 1 开始直到数组末尾。
每个 i 代表第 i 步。
嵌套 for 循环从第 0 个索引开始直到数组末尾。
对于每个第 i 次移动,如果索引 j 是 i 的倍数(j%i==0),则将该位置的 0 替换为 1。
对每个 i 继续此过程,直到数组末尾。
注意 - 索引从 i=1,j=1 开始,但数组索引从 0 到 N-1。所以每次都会转换arr[j1]。
最后再次遍历整个数组,数no。其中包含 1 并存储在计数中。
- 返回所需结果的计数。
示例
实时演示
'#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