n的阶乘-编程2.md

  • 计算阶乘n!: 注意处理结果溢出
  • 方法: 用数组来存储结果
/**
 * 计算阶乘n!: 注意处理结果溢出
 * 方法: 用数组来存储结果
 */
public class PowerN {

    // Time: O(n^2) Space: O(n)
    public int[] power(int n) {
        int[] result = new int[4000];
        int count = 1;
        int carry = 0; 
        result[0] = 1;
        for (int i = 2; i <= n; i++) {
            for (int j = 1; j <= count; j++) {
                int temp = result[j - 1] * i + carry;
                result[j - 1] = temp % 10;
                carry = temp / 10;
            }
            while (carry != 0) {
                result[++count - 1] = carry % 10;
                carry = carry / 10;
            }
        }

        for (int index = count; index > 0; index--) {
            System.out.print(result[index - 1]);
        }
        System.out.println();
        return result;
    }


    // 求1-100的阶乘
    public static void main(String[] args) {
        int n = 100;
        PowerN sol = new PowerN();
        for (int i = 1; i <= n; i++) {
            sol.power(i);

        }
    }
}


posted on 2017-04-12 19:55  BYRHuangQiang  阅读(323)  评论(0编辑  收藏  举报

导航