PAT乙級1008 陣列元素迴圈右移問題 (20分)
阿新 • • 發佈:2020-07-19
#include<stdio.h> int main(){ int n,k; scanf("%d %d",&n,&k); k = k%n; int a[1000]; if(n == 1){ int t; scanf("%d",&t); printf("%d",t); } else{ int rear = n-1; int front = 0; for(int i = 0;i<n;i++){ scanf("%d",&a[i]); } front+=k; rear = rear-k+1; for(int i =rear;i<n;i++){ printf("%d ",a[i]); } int j = 0; while(j!=rear-1){ printf("%d ",a[j]); j++; } printf("%d",a[rear-1]);} return 0; }
上面的 寫法其實是比較複雜的,是通過真正的對陣列進行右移來實現,以下的寫法是通過控制列印順序來實現“右移”,不過值得注意的是:題目沒有規定右移的大小,當右移大小超過陣列大小的時候需要對右移的大小進行一次轉換取模,使之小於陣列大小
1 #include <iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 int main() 6 { 7 int m, n; 8 cin >> m >> n; 9 int a[110]; 10 n = n % m; 11 for (int i = 0; i < m; i++) { 12 cin >> a[i]; 13 }14 for (int i = m - n; i < m; i++) { 15 cout << a[i]<<" "; 16 } 17 for (int i = 0; i < m - n; i++) { 18 cout << a[i]; 19 if (i != m - n - 1) { 20 cout << " "; 21 } 22 } 23 return 0; 24 }