课程作业02关于递归

1.(1)设计思想。

设计一个方法计算n!,再设计一个方法计算c(n,k),

调用这两个方法。

(2)程序流程图。

(3)程序源代码

import java.util.Scanner;


public class HomeWork11 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in );
int n=scanner.nextInt();
Scanner scanner2 = new Scanner(System.in );
int k=scanner2.nextInt();
g(n,k);
}
public static void g(int a,int b){
int c=f(a)/(f(b)*f(a-b));
System.out.println(c);
}
public static int f(int a){

int jieguo=1;
if(a>1)
{
jieguo=a*f(a-1);
f(a-1);
}
else if(a==1){
jieguo=1;
}
else {
System.out.println("输入错误,请重新输入");
jieguo=0;
}
return jieguo;
}
}

import java.util.Scanner;


public class HomeWork12 {
public static int c[][]=new int[100][100];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in );
int n=scanner.nextInt();
Scanner scanner2 = new Scanner(System.in );
int k=scanner2.nextInt();
c(n,k);
}
public static void c(int n, int k) {
c[0][0]=1;//初始化
c[1][0]=1;//初始化
c[1][1]=1;//初始化
for(int i=2;i<=n;i++)
{
c[i][0]=1;
c[i][i]=1;//初始化每行 杨辉三角的两边的值
for(int j=1;j<=i;j++)
{
c[i][j]=c[i-1][j-1]+c[i-1][j];
}
}
System.out.println("组合数的结果是:"+c[n][k]);
}
}

import java.util.Scanner;


public class HomeWork13 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in );
int n=scanner.nextInt();
Scanner scanner2 = new Scanner(System.in );
int k=scanner2.nextInt();
System.out.println("结果是"+ditui(n,k));
}
public static int ditui(int a,int b){
if(a<0||b<0||a<b){
return 0;
}
if(a==b){
return 1;
}
if(b==1){
return a;
}
return ditui(a-1,b)+ditui(a-1,b-1);
}
}

(4)结果截图

2.汉诺塔

(1)设计思想

根据数学模型设计先设计一个方法实现*盘到*盘的转移,再根据数学知识,实现盘子从A到C;

(2)程序流程图

(3)源程序代码

import java.util.Scanner;


public class Hannuota {
static Scanner scanner = new Scanner(System.in );
static int n=scanner.nextInt();
public static void moveDish(int level, char from, char inter, char to) {
if (level == 1) {
System.out.println("从" + from + " 移动盘子" + level + " 号到" + to);
} else {
moveDish(level - 1, from, to, inter);
System.out.println("从" + from + " 移动盘子" + level + " 号到" + to);
moveDish(level - 1, inter, from, to);
}
}
public static void main(String[] args) {
int nDisks = n;
moveDish(nDisks, 'A', 'B', 'C');
}
}

(4)实验结果

3.回文数

(1)设计思想

把一个整数的各个数位分离出来转换成字符数组:比如1234转换成{'1', '2' ,'3', '4'}
然后对这个数组进行比较,第1个元素和最后一个元素比较,第2个和倒数第2个比较,一旦不相等,就return false
(2)程序流程图
(3)程序源代码

import java.util.Scanner;
public class Huiwenshu {
static Scanner scan = new Scanner(System.in);
static String str=scan.next();
public static boolean isPalindrome(String s,int i,int j){
if(i > j)
throw new IllegalArgumentException();
if(i == j)
return true;
else{
return (s.charAt(i) == s.charAt(j)) && isPalindrome(s,i+1,j-1);
}
}

public static void main(String[] args){
String test = str;
int i = 0;
int j = test.length() - 1;
System.out.println(test + " is Palindrome? " + Huiwenshu.isPalindrome(test, i, j));
}
}

 (4)结果

文学使思想充满血与肉,他比科学和哲学更能给予思想以巨大的明确性和说明性。
原文地址:https://www.cnblogs.com/zpsblog/p/7668640.html