菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
340
0

有n个整数,使其前面各数顺序向后移n-m个位置,最后m个数变成最前面的m个数

原创
05/13 14:22
阅读数 80301

题目:有n个整数,使其前面各数顺序向后移n-m个位置,最后m个数变成最前面的m个数

public class 第三十六题数组向后移m个位置 {
    public static void main(String[] args) {
        int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
        int n = a.length;
        System.out.print("请输入向后移动的位数: ");
        Scanner in = new Scanner(System.in);
        int m = in.nextInt();
        in.close();
        if (m < 1 ) {
            System.out.println("输入的范围错误");
        } else if(m > a.length){
                m = m % n;
                move(a, m);
        } else { 
            move(a, m);
        }
        
        System.out.println(Arrays.toString(a));
    }

    public static void move(int[] a,int m) {
        int n = a.length;
        int[] b = new int[n-m];
        int len = n - m; //需要挪动的长度
        //保存最后n-m个数字
        int j = 0;
        for(int i = m; i < n; i++,j++) {
            b[j] = a[i];
        }
        //把前面的m个向后移动
        for(int i=0; i < m; i++) {
            a[i+len] = a[i];
        }
        //把保存的数字拷贝的数组前面
        for(int k = 0; k < len; k++) {
            a[k] = b[k];
        }
    }
}

 

发表评论

0/200
340 点赞
0 评论
收藏