`
fys124974704
  • 浏览: 139037 次
  • 性别: Icon_minigender_1
  • 来自: 火星
社区版块
存档分类
最新评论

精简之美

    博客分类:
  • Java
阅读更多

有一条阶乘的问题,就是怎么去写才能让代码最少,最精简!我想了很久,发现使用递归是最精简的写法!

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 精简的代码看上去才是让人最赏心悦目的!

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics