使用递归方法算阶乘、累加、十进制转二进制
階乘(factorial)
public class C8 { public static void main(String[] args) { System.out.println(factorial(10)); } public static int factorial(int n){ if(n==1) return 1; else return n*factorial(n-1); } }
累加求和(sum)
public class C8 { public static void main(String[] args) { System.out.println(sum(10)); } public static int sum(int n){ if(n==1) return 1; else return n+sum(n-1); } }
十進制轉二進制(DecimalToBinary)
public class C8 { public static void main(String[] args) { DecimalToBinary(10); } public static void DecimalToBinary(int n){ if(n>0){ DecimalToBinary(n/2); System.out.print(n%2); } } }