java基础:11.1 递归
发布日期:2022-04-04 06:36:32 浏览次数:18 分类:博客文章

本文共 2263 字,大约阅读时间需要 7 分钟。

之前学C语言时对递归有了较多了解,这部分主要把题目的代码都自己实现一遍。知识点不再记录了

import java.io.File;import java.util.Scanner;public class ComputeFactorial {	public static void main(String[] args) {		// TODO Auto-generated method stub				String directory = "f:\\java";		System.out.println(getSize(new File(directory)) + " bytes") ;				double [] list = { 2.5,1,5,8,3.1,5.5,6.8};		recursionSort(list);		for (double e:list)			   System.out.println(e);  		System.out.println("key = 3.1 , after BinarySearch fine the index = " + recursiveBinarySearch(list,3.1) );		String s = "II I";		System.out.println(" \""+s +" \" is isPalindrome = " + isPalindrome(s));		int fibonacci_index = 10;		System.out.println(" while index = " + fibonacci_index + " ,the fibonacci data = " + fibonacci(fibonacci_index));		int factorialN = 5;		System.out.println(" while N = " + factorialN + " ,the factorial result = " + factorial(factorialN));			}		private static long getSize(File file) {		long size = 0;				if (file.isDirectory()) {			File[] files = file.listFiles();			for (int i = 0; files != null && i < files.length; i++)				size += getSize(files[i]);		}		else  size += file.length();			return size;	}	public static int recursiveBinarySearch(double []list, double key) {		int low = 0;		int high = list.length-1;		return recursiveBinarySearch(list,low,high,key);	}	private static int recursiveBinarySearch(double []list, int low, int high, double key) {		if (low > high) return -low-1;		int mid = (low+high)/2;		if(key < list[mid]) 			return recursiveBinarySearch(list,low,mid-1,key);		else if(key > list[mid])			return recursiveBinarySearch(list,mid+1,high,key);		else		    return mid ;	}			/* --------  sort  ------- */	public static void recursionSort(double []list) {		recursionSort(list,0,list.length-1);	}		private static void recursionSort(double []list,int low,int high) {		if(low
= high) return true; else if(s.charAt(low) != s.charAt(high)) return false; else return isPalindrome(s,low+1,high-1); } /* --- fibonacci --- */ public static int fibonacci(int index) { if(index==0) return 0; else if(index==1) return 1; else return fibonacci(index-1)+fibonacci(index-2); } /* --- factorial --- */ public static long factorial(int n) { if(n==0) return 1; else return n*factorial(n-1); }}

 

转载地址:https://www.cnblogs.com/l20902/p/10610899.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:4.3 阻塞赋值与非阻塞赋值
下一篇:4.3 Verilog练习(3)

发表评论

最新留言

不错!
[***.144.177.141]2024年04月17日 11时11分18秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章