循环右移
数组中有N个整数,向右移动M位,输出移动之后的数组
输入:
6 2
1 2 3 4 5 6
输出:
5 6 1 2 3 4
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int a[80];
int main(){
int n, m;
int count = 0;
cin >> n >> m;
m = m % n; //修正m,保证m比n小
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = n - m; i < n; i++)
{
cout << a[i];
count++;
if (count < n)
cout << " ";
}
for (int i = 0; i < n - m; i++)
{
cout << a[i];
count++;
if (count < n)
cout << " ";
}
system("pause");
return 0;
}
字符串循环右移(正)或左移(负)
int main()
{
string s;
int k;
while (cin >> s >> k)
{
int n = s.size();
k = (n + k % n) % n; //为了同时处理正负两种情况
cout << s.substr(n - k) + s.substr(0, n - k) << endl;
}
return 0;
}
==================(方法2)=========================
循环右移
int a[80];
int main(){
int n, m;
int temp;
cin >> n >> m;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < m; i++)
{
temp = a[n - 1];
for (int j = n - 1; j>0; j--)
a[j] = a[j - 1];
a[0] = temp;
}
for (int i = 0; i < n; i++)
cout << a[i] << "";
return 0;
}
循环左移
for(i=0;i<m;i++) //外循环 控制内循环次数以及最低位到最高位的移位
{
temp=a[0]; //最低位被更新之前存到变量temp中
for(j=0;j<n-1;j++) //内循环 从次低位开始 依次将数向低位移动一位
a[j]=a[j+1];
a[n-1]=temp; //更新最高位
}
===============扩展====================
给定两个字符串s1,s2,请返回bool值代表s2是否由s1旋转而成。字符串中字符为英文字母和空格,区分大小写,字符串长度小于等于1000。
测试样例:
"Hello world","worldhello "
返回:false
"waterbottle","erbottlewat"
返回:true
bool check(string s1, string s2)
{
int size1 = s1.size();
int size2 = s2.size();
if (size1 == 0 || size2 == 0)
return false;
string str = s1 + s1;
if (str.find(s2) == -1)
{
return false;
}
return true;
}
浙公网安备 33010602011771号