Factorial 计算阶乘
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example: 5! = 5 * 4 * 3 * 2 * 1 = 120. By convention the value of 0! is 1.
Write a function to calculate factorial for a given input. If input is below 0 or above 12 throw an exception of type ArgumentOutOfRangeException (C#) or IllegalArgumentException (Java).
More details about factorial can be found here: http://en.wikipedia.org/wiki/Factorial
刚开始没有注意题目的提示,可以直接判断大于12,就溢出了。想到了使用checked关键字来检查是否溢出。
https://msdn.microsoft.com/zh-cn/library/74b4xzyw.aspx checked关键字的用法
public static class Kata { public static int Factorial(int n) { try { return Recursion(n); } catch { throw; } } public static int Recursion(int n) { if (n < 0) { throw new ArgumentOutOfRangeException(); } try { int factorial = 1; if (n >= 2) { checked { factorial = n * Recursion(n - 1); } } return factorial; } catch { throw new ArgumentOutOfRangeException(); } } }
其他人的解法:
public static int Factorial(int n) { if(n < 0 || n > 12) throw new ArgumentOutOfRangeException(); return n > 0 ? n * Factorial(n - 1) : 1; }
using System; using System.Linq; public static class Kata { public static int Factorial(int n) { if(n < 0 || n > 12) throw new ArgumentOutOfRangeException(); return Enumerable.Range(1, n).Aggregate(1, (x,y) => x * y); } }
时间: 2024-09-28 22:18:34