/**
* 简单实现阶乘
* @param n
* @return
*/
public static double getFactorial(double n) {
for(double i = n - 1;i > 0;i-- ){
n *= i;
}
return n;
}
/**
* 求阶乘
* n!=n*(n-1)*(n-2)*...*1
* @param n
* @return
*/
public static int getFactorialValue(int n){
if(n == 1){
return 1;
} else {
return getFactorialValue(n -1)*n;
}
}
/**
* 用递归实现斐波那契数列,适用于求解比较小的位置数值
* 0 1 1 2 3 5 8 13 21...
* @param n
* @return
*/
public static int getFibonacciValue(int n){
if(n<=0) return 0;
if(n<=2){
return 1;
} else {
return getFibonacciValue(n-1) + getFibonacciValue(n-2);
}
}
/**
* 列出某个目录下所有子目录和文件
* @param path
* @return
*/
public static void getDir(String path) throws Exception{
File file = new File(path);
if(file.isDirectory()){
System.out.println("Dir" + file.getPath());
File[] fileArr = file.listFiles();
for (File f : fileArr) {
getDir(f.getPath());
}
}else if (file.isFile()){
System.out.println("File" + file.getPath());
}else {
throw new Exception(file.getPath() + "非Dir非File?!");
}
}
/**
* 汉诺塔
* func:
* if n!=0 then ;预定值
* func(n-1, a, c, b) ;将n-1个盘子由a移动到b,以c为辅助柱子(注意参数顺序)
* move a[n] to c ;将a上的最后一个盘子移动到c
* func(n-1, b, a, c) ;将n-1个盘子由b移动到c,以a为辅助柱子
* endif ;完成
* @param n
* @param a
* @param b
* @param c
*/
public static void getHanoi(int n, String a, String b, String c){
if(n == 1){
System.out.println("移动盘子 " + n + " 从 " + a + " 到 " + c);
}else {
getHanoi(n-1, a, c, b);
System.out.println("移动盘子 " + n + " 从 " + a + " 到 " + c);
getHanoi(n-1, b, a, c);
}
}
/**
* 二分法查找值 : 原理就是找中间值
* 一定是有序表,升序降序都可以
*
* @param array 有序数组,但不限于数组
* @param start 开始查找的数组下标
* @param end 结束查找的数组下标
* @param searchValue 要搜索的值
* @return
*/
public static int search(int[] array, int start, int end, int searchValue){
if (array != null && array.length > 0){
int middle = (start + end) / 2;
int middleValue = array[middle];
if (searchValue == middleValue){
return middle;
}else if (searchValue < middleValue){
//查询值小于中值,在中值前面再次搜索,缩小范围
return search(array, start, middle-1, searchValue);
}else {
//查询值大于中值,在中值后面再次搜索,缩小范围
return search(array, middle+1, end, searchValue);
}
}else {
return -1;
}
}