1. 程式人生 > >將課程作業01、02、03的設計思想、源程序代碼和結果截圖整理成一篇博文。。

將課程作業01、02、03的設計思想、源程序代碼和結果截圖整理成一篇博文。。

top exception 漢諾塔 一個數 resource valueof val 作業 回文數

信1605-3 於丁一 20163578

使用組合數公式利用n!來計算

設計思想:首先要判斷一個數的階乘如何表達,然後調用方法用組合數公式,最後求出組合數。

package n的階乘;

public class number {
public static void main(String[] args){
int a=4;
int b=5;
System.out.println("C("+a+","+b+")="+gNum(a,b));
}
public static int gNum(int m,int n){
if(m==0||m==n)
return 1;
else return f(n)/(f(m)*f(n-m));
}
public static int f(int z){
if(z==1)
return 1;
else return z*f(z-1);
}
}

技術分享

技術分享

使用遞推的方法用楊輝三角形計算

設計思想:首先需要構建一個楊輝三角,最後的結果就是楊輝三角形中的一個數,最後輸出對應的數就可以

package 使用遞推的方法用楊輝三角形計算;
import java.util.Scanner;
import java.math.BigInteger;
public class Number {

public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner=new Scanner(System.in);
System.out.println("輸入兩個數並用空格隔開");
int n=scanner.nextInt();
int k=scanner.nextInt();
BigInteger[][] a=new BigInteger[n][n];
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if((i==0)&&(j==0))
a[i][j]=BigInteger.valueOf(1);
else if(j==0||j==i)
a[i][j]=BigInteger.valueOf(1);
else if(j<=i)
a[i][j]=a[i-1][j-1].add(a[i-1][j]);
else
a[i][j]=BigInteger.valueOf(0);

}
}

System.out.println("n!/(k!*(n-k)!)="+a[n-1][k-1]);
}

使用遞歸的方法用組合數遞推公式計算

設計思想:首先定義組合數中的兩個數,調用方法,並且在方法中在調用自己,完成遞歸,最後輸出正確的結果。

package 使用遞歸的方法用組合數遞推公式計算;

public class Number {
public static void main(String[] args){
int a=4;
int b=5;
System.out.println("C("+a+","+b+")="+gNum(a,b));
}
public static int gNum(int m,int n){
if(m==0||m==n)
return 1;
else return gNum(m-1,n-1)+gNum(m,n-1);
}
}

技術分享

遞歸編程解決漢諾塔問題。用Java實現

設計思想:利用遞歸,先留一個圓盤,把n-1個圓盤先移動,把最後一個圓盤移到c上,以這樣的方法移動。

public class Number {

public static void main(String[] args) {
int disk = 5;
move(disk, ‘A‘, ‘B‘, ‘C‘);
}

private static void move(int topN, char from, char inter, char to) {
if (topN == 1) {
System.out.println("Disk 1 from " + from + " to " + to);
} else {
move(topN - 1, from, to, inter);
System.out.println("Disk " + topN + " from " + from + " to " + to);
move(topN - 1, inter, from, to);
}


}

}

技術分享

使用遞歸方式判斷某個字串是否是回文( palindrome )

設計思想:比較首尾的字符,要是相同在繼續比較第二個字符,按照這樣的方法一直比較,知道相同,輸出結果。

package 回文;

import java.util.Scanner;

public class Number {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
String s = in.nextLine();
int i = 0;
int j = s.length() - 1;
System.out.println(s + " 是回文數麽? " + Number .gNum(s, i, j));
}

public static boolean gNum(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)) && gNum(s,i+1,j-1);
}
}

}

技術分享

技術分享

將課程作業01、02、03的設計思想、源程序代碼和結果截圖整理成一篇博文。。