原题链接:[编程入门]自定义函数之数字后移
参考代码:
public void backward1 () {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int step = sc.nextInt();
//第一层:遍历前n-step个元素
//第二层:每遍历一个元素,就与后面step个元素相交换位置
for (int i = n-step-1; i >= 0; i--) {
int x = step;
for (int j = i; x-- > 0; j++) {
int tmp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = tmp;
}
}
for (int i = 0; i < n; i++) {
System.out.println(arr[i]);
}
}
public void backward2 () {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = sc.nextLine();
int step = sc.nextInt();
String res = str.substring(n-step)+str.substring(0,n-step-1);
for (int i = 0; i < n; i++) {
System.out.print(res.charAt(i));
}
}
public void backward3 () {
int N =10;
int[] a = new int[N];
Scanner s = new Scanner(System.in);
System.out.println("请输入10个整数:");
for(int i=0; i<N; i++) {
a[i] = s.nextInt();
}
System.out.print("你输入的数组为:");
for(int i=0; i<N; i++) {
System.out.print(a[i] + " ");
}
System.out.print("\n请输入向后移动的位数:");
int m = s.nextInt();
int[] b = new int[m];
for(int i=0; i<m; i++) {
b[i] = a[N-m+i];
}
for(int i=N-1; i>=m; i--) {
a[i] = a[i-m];
}
for(int i=0; i<m; i++) {
a[i] = b[i];
}
System.out.print("位移后的数组是:");
for(int i=0; i<N; i++) {
System.out.print(a[i] + " ");
}
}
public void backward4 () {
System.out.println("输入n个整数,再输入m,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数");
//获取用户的输入,并解析为一个数组
Scanner sc = new Scanner(System.in);
System.out.println("请直接输入数组元素,(以逗号作为间隔)");
String str = sc.next();
//分割用户输入得到一个字符串数组
String[] strs = str.split(",|,");
// 遍历这个字符串数组,将每个字符串解析为一个Integer,并装到Integer数组中
int[] nums = new int[strs.length];
int[] exchange = new int[nums.length];
int m = 0;
try {
for (int i = 0; i < strs.length; i++) {
nums[i] = Integer.parseInt(strs[i]);
}
//新建一个长度一样的数组
System.out.println("原数组:" + Arrays.toString(nums));
//让用户输入m的值
System.out.println("请输入向后移动的位数m:");
m = sc.nextInt();
} catch (NumberFormatException e) {
System.out.println("你输入有误,请输入数字,其它字符不支持");
}
// 遍历两个数组,因为长度一样,所以一个for循环就足够
for (int i = 0; i < nums.length; i++) {
// m个数前的情况
if (i < nums.length - m) {
exchange[i + m] = nums[i];
} else if (i >= nums.length - m) {
// 最后的m个数放到新数组的最前面
for (int j = 0; j < m; j++) {
exchange[j] = nums[nums.length - m + j];
}
// 转换完成,退出循环
break;
}
}
// 输出转换后的结果
System.out.println("转换后:" + Arrays.toString(exchange));
}
//取巧方法,不改变原数组,直接按需求打印
public void backward5 () {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr1 = new int[n];
for (int i = 0; i < n; i++) {
arr1[i] = sc.nextInt();
}
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
System.out.print(arr1[n - m + i] + " ");
}
for (int i = 0; i < n - m; i++) {
System.out.print(arr1[i] + " ");
}
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复