Java 方法

一、方法重载

 1 public class text {
 2 
 3     public static void main(String[] args) {
 4         System.out.println("The square of integer 7 is " + square(7));
 5         System.out.println("
The square of double 7.5 is " + square(7.5));
 6     }
 7     public static int square(int x) {
 8         return x * x;
 9     }
10     public static double square(double y) {
11         return y * y;
12     }
13 }

  方法可以重载,但方法名不变,返回值类型和参数类型可以变。

二、组合数计算

  1、使用组合数公式利用n!来计算

  

 1 //使用组合数公式利用n!来计算
 2 public class CombinatorialNumber {
 3     public static void main(String[] args) {
 4         int upNumber=3;
 5         int downNumber=6;
 6         System.out.println("C["+downNumber+"]["+upNumber+"]="+
 7         combNumCal(upNumber,downNumber));
 8     }
 9     public static int combNumCal(int upN,int downN){
10         if(upN==0||upN==downN)
11             return 1;
12         return f(downN)/(f(upN)*f(downN-upN));
13     }
14     public static int f(int x){                     //计算阶乘
15         if(x==1) return 1;
16         else return x*f(x-1);
17     }
18 }

  2、使用递归的方法用组合数递推公式计算

  

 1 //使用递归的方法用组合数递推公式计算
 2 class CombinatorialNumber {
 3 
 4     public static void main(String[] args) {
 5         int upNumber=2;
 6         int downNumber=5;
 7         System.out.println("C["+downNumber+"]["+upNumber+"]="+
 8         combNumCal(upNumber,downNumber));
 9     }
10     public static int combNumCal(int upN,int downN){
11         if(upN==0||downN==upN)
12             return 1;
13         return combNumCal(upN-1,downN-1)+combNumCal(upN,downN-1);
14     }
15 }

三、汉诺塔问题

 1 public class TowersOfHanoi {
 2 
 3     public static void main(String[] args) {
 4         int disks=3;               //盘子总数
 5         int sourceColumn=1;           //第一个珠子  即所有盘子出事的位置
 6         int secondColumn=2;           //盘子中转的柱子
 7         int finalColumn=3;           //盘子最终的位置
 8           SolveHanoi(disks,sourceColumn,secondColumn,finalColumn);
 9     }
10     public static void SolveHanoi(int disk,int first,int second,int third){
11         if(disk==1)
12             System.out.println(first+" ---> "+third);
13         else{
14             SolveHanoi(disk-1,first,third,second);
15             System.out.println(first+" ---> "+third);
16             SolveHanoi(disk-1,second,first,third);
17         }
18     }
19 }

原文地址:https://www.cnblogs.com/yifengyifeng/p/5966055.html