【程序1】 題目:求1+2!+3!+...+20!的和
1.程序分析:此程序只是把累加變成了累乘。
public class Ex21 {static long sum = 0;static long fac = 0;public static void main(String[] args) {long sum = 0;long fac = 1;for(int i=1; i<=10; i++) {fac = fac * i;sum += fac;}System.out.println(sum);}}
【程序2】 題目:利用遞歸方法求5!。
1.程序分析:遞歸公式:fn=fn_1*4!
import java.util.Scanner;public class Ex22 {public static void main(String[] args) {Scanner s = new Scanner(System.in);int n = s.nextInt();Ex22 tfr = new Ex22();System.out.println(tfr.recursion(n));}public long recursion(int n) {long value = 0 ;if(n ==1 || n == 0) {value = 1;} else if(n > 1) {value = n * recursion(n-1);}return value;}}
【程序3】 題目:有5個人坐在一起,問第五個人多少歲?他說比第4個人大2歲。問第4個人歲數(shù),他說比第3個人大2歲。問第三個人,又說比第2人大兩歲。問第2個人,說比第一個人大兩歲。最后問第一個人,他說是10歲。請問第五個人多大?
1.程序分析:利用遞歸的方法,遞歸分為回推和遞推兩個階段。要想知道第五個人歲數(shù),需知道第四人的歲數(shù),依次類推,推到第一人(10歲),再往回推。
public class Ex23 {static int getAge(int n){if (n==1){return 10;}return 2 + getAge(n-1);}public static void main(String[] args) {System.out.println("第五個的年齡為:"+getAge(5));}}
【程序4】 題目:給一個不多于5位的正整數(shù),要求:一、求它是幾位數(shù),二、逆序打印出各位數(shù)字。
import java.util.Scanner;public class Ex24 {public static void main(String[] args) {Ex24 tn = new Ex24();Scanner s = new Scanner(System.in);long a = s.nextLong();if(a < 0 || a > 100000) {System.out.println("Error Input, please run this program Again");System.exit(0);}if(a >=0 && a <=9) {System.out.println( a + "是一位數(shù)");System.out.println("按逆序輸出是" + 'n' + a);} else if(a >= 10 && a <= 99) {System.out.println(a + "是二位數(shù)");System.out.println("按逆序輸出是" );tn.converse(a);} else if(a >= 100 && a <= 999) {System.out.println(a + "是三位數(shù)");System.out.println("按逆序輸出是" );tn.converse(a);} else if(a >= 1000 && a <= 9999) {System.out.println(a + "是四位數(shù)");System.out.println("按逆序輸出是" );tn.converse(a);} else if(a >= 10000 && a <= 99999) {System.out.println(a + "是五位數(shù)");System.out.println("按逆序輸出是" );tn.converse(a);}}public void converse(long l) {String s = Long.toString(l);char[] ch = s.toCharArray();for(int i=ch.length-1; i>=0; i--) {System.out.print(ch[i]);}}}
以上就是天津卓眾教育java培訓(xùn)機(jī)構(gòu)的小編針對“Java入門算法題目,初學(xué)者必備”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為你服務(wù)。