读书人

分分钟 面试题 n! 毕竟考什么

发布时间: 2013-03-28 10:20:24 作者: rapoo

分分钟 面试题 n! 到底考什么?

关于n!每个程序员都能分分钟搞定

方法一:最简单的方法就是递推相乘:

代码如下,main中加入了很多输入参数的判断: 输入必须是一个 数字 :

package test.ms;import java.math.BigInteger;public class TestFactorialRecursion {  public static void main(String[] args) {   try{  if(args == null || args.length >1 || args.length == 0){ System.out.println("Please input  one  number");  }else{  int  n = Integer.parseInt(args[0]);  BigInteger   m = new BigInteger(String.valueOf(n)); BigInteger  result = factorial2(m); System.out.println(result);  }    }catch(NumberFormatException e){  e.printStackTrace();  System.out.println("Please  intput  number  formate ");  }  }  public  static  BigInteger  factorial2(BigInteger  n){  BigInteger   value1 = new  BigInteger("1");  if( value1.compareTo(n) == 0){  return   value1;  }else{  BigInteger  temp = new  BigInteger(String.valueOf(n));  return   temp.multiply(factorial2(temp.subtract(value1)));  }    }}

由于用到了递归,以上输入参数和返回类型都采用BigInteger类型:

BigInteger中提供了 关于 BigInteger 的加减乘除等一些基本运算:

上面的例子中:

用到了 multiply(BigInteger val) 和subtract(BigInteger val) 方法 用于 乘和 减

输入

100!=93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

依然能够准确计算出来。

主要考察递归,基本类型值的范围。






读书人网 >编程

热点推荐