Factorial

http://www.lintcode.com/en/problem/factorial/
请参阅 Big Integer multiplication

public class Solution {
    /*
     * @param : an integer
     * @return:  the factorial of n
     */
    public String factorial(int n) {
        // write your code here
        String res = "1";
        for (int i = 2; i <= n; i++) {
            res = multiply(res, String.valueOf(i));
        }
        return res;
    }

    public String multiply(String num1, String num2) {
        // write your code here
        int[] res = new int[num1.length() + num2.length()];
        char[] chars2 = num2.toCharArray();
        char[] chars1 = num1.toCharArray();
        int index = 0;
        for (int i = chars2.length - 1; i >= 0; i--) {
            int a = chars2[i] - '0';
            for (int j = chars1.length - 1; j >= 0; j--) {
                int b = chars1[j] - '0';
                b *= a;
                int tempIndex = res.length - 1 - (chars2.length - 1 - i) - (chars1.length - 1 - j);
                res[tempIndex] += b;
                if (res[tempIndex] >= 10) {
                    res[tempIndex - 1] += res[tempIndex] / 10;
                    res[tempIndex] %= 10;
                }
                index = tempIndex;
            }
        }
        index--;
        while (res[index] >= 10) {
            res[index - 1] += res[index] / 10;
            res[index] %= 10;
            index--;
        }
        while (res[index] == 0) {
            index++;
            if (index >= res.length) {
                return "0";
            }

        }
        StringBuilder sb = new StringBuilder();
        for (int i = index; i < res.length; i++) {
            sb.append(res[i]);
        }
        return sb.toString();
    }

}

你可能感兴趣的:(Factorial)