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