JAVA经典算法面试10题及答案
【程序1】题目:古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第四个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
1.程序分析: 兔子的规律为数列1,1,2,3,5,8,13,21….public class exp2{public static void main{int i=0;for);}public static int f{ifreturn 1;elsereturn f+f;}}或public class exp2{public static void main{int i=0;math mymath = new math;for);}}class math{public int f{ifreturn 1;elsereturn f+f;}}
【程序2】题目:判断101-200之间有多少个素数,并输出所有素数。 1.程序分析:判断素数的方法:用一个数分别去除2到sqrt,如果能被整除,
则表明此数不是素数,反之是素数。public class exp2{public static void main{int i=0;math mymath = new math;forif==true);}}class math{public int f{ifreturn 1;elsereturn f+f;}public boolean iszhishu{forif return false;return true;}}
【程序3】题目:打印出所有的 “水仙花数 “,所谓 “水仙花数 “是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个 “水仙花数 “,因为153=1的三次方+5的三次方+3的三次方。
1.程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。public class exp2{ public static void main{ int i=0; math mymath = new math; for if==true) ; }}class math{ public int f { if return 1; else return f+f; } public boolean iszhishu { for if return false; return true; } public boolean shuixianhua { int i=0,j=0,k=0; i=x / 100; j= /10; k=x % 10; if return true; else return false; }}
【程序4】题目:将一个正整数分解质因数。例如:输入90,打印出90=2*3*3*5。 程序分析:对n进行分解质因数,应先找到一个最小的质数k,然后按下述步骤完成:
如果这个质数恰等于n,则说明分解质因数的过程已经结束,打印出即可。 如果n k,但n能被k整除,则应打印出k的值,并用n除以k的商,作为
新的正整数你,重复执行第一步。
如果n不能被k整除,则用k+1作为k的值,重复执行第一步。public class exp2{public exp2{} public void fengjie{ for{ if{ ; fengjie; } } ; ;s:///不能少这句,否则结果会出错 } public static void main{ string str=““; exp2 c=new exp2;
str=;
int n;