JavaSE methods recursive exercises 】 【 create and use of the array

Can this code be any cooler? 2022-08-06 16:25:05 阅读数:919

javasemethodsrecursiveexercisescreate

1.递归求 N 的阶乘

public static int fuc (int n){

if (n == 1){

return 1;
}
int tmp = n*fuc(n-1);
return tmp;
}
public static void main(String[] args) {

System.out.println(fuc(4));
}

2.递归求 1 + 2 + 3 + … + 10

public static int sum(int n){

if (n == 1){

return 1;
}
int tmp = n+sum(n-1);
return tmp;
}
public static void main(String[] args) {

System.out.println(sum(10));
}

3.按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) (递归)

public static void print(int n){

if (n > 9){

print(n/10);
}
System.out.print(n%10 + " ");
}
public static void main(String[] args) {

int n =1234;
print(n);
}

4.写一个递归方法,输入一个非负整数,返回组成它的数字之和

public static int ret(int n){

if (n > 0){

return n%10 + ret(n/10);
}
return 0;
}
public static void main(String[] args) {

int n =1234;
System.out.println(ret(n));;
}

5.递归求斐波那契数列的第 N 项

public static int fib(int n){

if (n ==1 || n==2){

return 1;
}else{

return fib(n-1)+fib(n-2);
}
}
public static void main(String[] args) {

int n = 7;
System.out.println(fib(n));
}

6.递归求解汉诺塔问题

public static void hanio(int n,char pos1,
char pos2,char pos3) {

if(n == 1) {

move(pos1,pos3);
return;
}
hanio(n-1,pos1,pos3,pos2);
move(pos1,pos3);
hanio(n-1,pos2,pos1,pos3);
}
public static void move(char pos1,char pos2) {

System.out.print (pos1+" -> " + pos2+" ");
}
public static void main(String[] args) {

hanio(4,'A','B','C');
}

7.创建一个 int 类型的数组, 元素个数为 100, 并把每个元素依次设置为 1 - 100

public static void main(String[] args) {

int [] array = new int[100];
for (int i = 0; i < array.length; i++){

array[i] = i+1;
}
String ret = Arrays.toString(array);
System.out.println(ret);
}

8.实现一个方法 printArray, 以数组为参数, 循环访问数组中的每个元素, 打印每个元素的值.

public static void printArray(int[] array) {

for (int i = 0; i < array.length; i++) {

System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {

int[] array = {
1, 2, 3, 5, 6, 9, 8};
printArray(array);
}
copyright:author[Can this code be any cooler?],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/218/202208061617592622.html