Java经典算法40例(二十二)

来源:互联网 发布:光纤交换机查看端口 编辑:程序博客网 时间:2024/06/02 02:09

题目:利用递归方法求5!。

代码:

/** * 递归求阶乘 * @author cheng * */public class TwentyTwo {    public int jiecheng(int n){        if(n==1||n==0)            return 1;        if(n>=2){            return n*jiecheng(n-1);        }        else{            return 0;        }    }    public static void main(String[] args){        TwentyTwo twentyTwo=new TwentyTwo();        int result=twentyTwo.jiecheng(5);        System.out.println("5!="+result);    }}

输出结果:

5!=120
原创粉丝点击