有一条阶乘的问题,就是怎么去写才能让代码最少,最精简!我想了很久,发现使用递归是最精简的写法!
public class Test {
public static void main(String[] args) {
System.out.println(fact2(7));
}
/* 递归写法 */
public static int fact(int n){
if( n == 0)
return 1;
else
return n*fact(n-1);
}
/* 非递归写法 */
public static int fact2(int n){
int sum = 1;
while( n >= 1){
sum *= n;
n -= 1;
}
return sum;
}
}
# 非递归
def fact2(n)
sum = 1
while(n >= 1)
sum *= n
n -= 1
end
return sum
end
# 递归
def fact(n)
if n == 0
1
else
n * fact(n-1)
end
end
puts fact(7)
无论是Java 还是 Ruby 精简的代码看上去才是让人最赏心悦目的!