美文网首页我家丫头的cpp
数组元素循环右移问题

数组元素循环右移问题

作者: 李药师_hablee | 来源:发表于2019-04-12 15:06 被阅读0次
  • 方法1
    main.cpp
#include<stdio.h>
#include<stdlib.h>
#include "shift_heard.h"

#define MAXN 100

int main()
{
    int number[MAXN], N, M;
    int i;
    scanf_s("%d%d", &N, &M);
    for (i = 0; i < N; i++)
    {
        scanf_s("%d", &number[i]);
    }
    M %= N;//当M大于等于N时转化成等价的小于N的数
    for (i = 0; i < M; i++)
    {
        shift(number, N);
    }
    for (i = 0; i < N; i++)
    {
        printf("%d ", number[i]);
    }

    system("pause");
    return 0;
}

shift_heard.h

#ifndef _shift_HEARD
#define _shift_HEARD

void shift(int Array[], int N);

#endif // !_shift_HEARD

shift.cpp

void shift(int Array[], int N)
{
    int i, ArrayEnd;

    ArrayEnd = Array[N - 1];
    for (i = N - 1; i > 0; i--)
    {
        Array[i] = Array[i - 1];
    }
    Array[0] = ArrayEnd;
}

输出

输出.png
  • 方法2
    main.cpp
#include<stdio.h>
#include<stdlib.h>
#include "shift_heard.h"

#define MAXN 100


int main()
{
    int number[MAXN], N, M;
    int i;
    scanf_s("%d%d", &N, &M);
    for (i = 0; i < N; i++)
    {
        scanf_s("%d", &number[i]);
    }
    M %= N;//当M大于等于N时转化成等价的小于N的数

    shift(number, N, M);

    for (i = 0; i < N; i++)
    {
        printf("%d ", number[i]);
    }

    system("pause");
    return 0;
}

shift.cpp

#define swap(a,b) a^=b,b^=a,a=a^b

void shift(int Array[], int N,int M)
{
    int i, j;

    if (M > 0 && M < N)
    {
        for (i = 0, j = N - 1; i < j; i++, j--)//逆转N个数据
        {
            swap(Array[i], Array[j]);
        }
        for (i = 0, j = M-1; i < j; i++, j--)//逆转前M个数据
        {
            swap(Array[i], Array[j]);
        }
        for (i = M, j = N - 1; i < j; i++, j--)//逆转後N-M个数据
        {
            swap(Array[i], Array[j]);
        }
    }
}

shift_heard.h

#ifndef _shift_HEARD
#define _shift_HEARD

void shift(int Array[], int N,int M);

#endif // !_shift_HEARD

输出

output.PNG

相关文章

  • 数组元素循环右移问题

    方法1main.cpp shift_heard.h shift.cpp 输出 方法2main.cpp shift....

  • 数组循环问题

    自测-3 数组元素循环右移问题一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移...

  • PAT-B 1008 数组元素循环右移问题(C语言)

    题目 链接:PAT (Basic Level) Practice 1008 数组元素循环右移问题 一个数组A中存有...

  • 1008 数组元素循环右移问题

    一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A中的数...

  • 1008数组元素循环右移问题

    问题描述:一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即...

  • 数组元素循环右移

    将一个int[]型数组右移k位,要求最小的空间占用。 一个数组A中存有N(N>0)个数, 在不允许使用任何另外数组...

  • 1008. 数组元素循环右移问题

    原题链接数组元素循环右移问题: 一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向...

  • 1008. 数组元素循环右移问题

    一个数组A中存有N(N>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(M>=0)个位置,即将A...

  • PTA 1008 数组元素循环右移问题

    题目 一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即将A...

  • 乙级|1008.数组元素循环右移问题

    题目描述 一个数组A中存有N(>0)个整数,在不允许使用另外数组的前提下,将每个整数循环向右移M(≥0)个位置,即...

网友评论

    本文标题:数组元素循环右移问题

    本文链接:https://www.haomeiwen.com/subject/ipucwqtx.html