输入n个数和输出调整后的b个数

问题及代码:


方法:

n个数往右移m格的步骤:

①把前n-m个数逆序②最后m个数逆序③所有n个数逆序。


* All rights reserved. 
* 文件名称:a.cpp 
* 作    者:单昕昕 
* 完成日期:2016年4月19日 
* 版 本 号:v1.0 
* 问题描述:有n个整数,使前面各数顺序向后移动m个位置,最后m个数变成最前m个数。
* 程序输入:数据个数n,n个数据、移动位置m。 
* 程序输出:移动后的数据。 
*/  
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include <iomanip>
#include<algorithm>
using namespace std;

void mv(int a[],int n,int m)
{
    int t,*p,*q;
    for(p=a,q=a+n-m-1; p<q; ++p,--q)
    {
        t = *p;
        *p = *q;
        *q = t;
    }
    for(p=a+n-m,q=a+n-1; p<q; ++p,--q)
    {
        t = *p;
        *p = *q;
        *q = t;
    }
    for(p=a,q=a+n-1; p<q; ++p,--q)
    {
        t = *p;
        *p = *q;
        *q = t;
    }
}
/*测试用例
10
1 2 3 4 5 6 7 8 9 10
2
*/
int main()
{
    int a[80];
    int m,i,n;
    cin>>n;
    for(i=0; i<n; i++)
        cin>>a[i];
    cin>>m;
    mv(a,n,m);
    for(i=0; i<n; i++)
        cout<<a[i]<<" ";
    return 0;
}
void reverse(int *a, int *b)
{
    for (; a<b; a++,b--)
    {
        int t = *a;
        *a = *b;
        *b = t;
    }
}

运行结果:



Note:反序函数:

void reverse(int *a, int *b)
{
    for (; a<b; a++,b--)
    {
        int t = *a;
        *a = *b;
        *b = t;
    }
}
void shift(int n, int *a, int m)
{
    reverse(a, a+(n-m-1));
    reverse(a+(n-m), a+(n-1));
    reverse(a, a+(n-1));
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值