Problem20

简介:

1.package com.yao.shuimu.euler;  
2.  
3.import java.util.ArrayList;  
4.import java.util.List;  
5.  
6./** 
7. * Created by IntelliJ IDEA. 
8. * User: shuimuqinghua77 
9. * Date: 11-12-15 
10. * Time: 下午1:25 
11. */  
12.public class Problem20 {  
13.  
14.    public static void main(String[] args) throws Exception {  
15.  
16.        byte[] result = digit(1);  
17.        for (byte i = 1; i <= 100; i++) {  
18.            result = multiply(digit(i), result);  
19.        }  
20.  
21.        int sum = 0;  
22.        for (byte digit : result) {  
23.            sum += digit;  
24.        }  
25.        System.out.println(sum);  
26.  
27.    }  
28.  
29.    private static byte[] multiply(byte[] multiplicand/**被乘数**/, byte[] multiplier) throws Exception {  
30.        if (multiplicand.length == 0 || multiplier.length == 0) {  
31.            throw new Exception("被乘数/乘数为空!!!");  
32.        }  
33.        if (multiplicand.length < multiplier.length) {  
34.            byte[] temp = multiplier;  
35.            multiplier = multiplicand;  
36.            multiplicand = temp;  
37.        }  
38.        byte[] result = new byte[multiplicand.length + multiplier.length];  
39.        for (int i = 0; i < multiplier.length; i++) {  
40.            for (int j = 0; j < multiplicand.length; j++) {  
41.                result[i + j] += (byte) (multiplier[i] * multiplicand[j]);  
42.            }  
43.            /**[29]->[9][2]进位**/  
44.            carry(result, 1 + multiplicand.length, i);  
45.        }  
46.        if (result[result.length - 1] == 0) {  
47.            byte[] resultDest = new byte[result.length - 1];  
48.            System.arraycopy(result, 0, resultDest, 0, result.length - 1);  
49.            return resultDest;  
50.        }  
51.  
52.        return result;  
53.    }  
54.  
55.    private static void carry(byte[] result, int length, int base) {  
56.        for (int i = base; i < length + base; i++) {  
57.            byte decade = (byte) (result[i] / 10);  
58.            if (decade >= 1) {  
59.                result[i + 1] += decade;  
60.                result[i] = (byte) (result[i] % 10);  
61.            }  
62.        }  
63.  
64.    }  
65.  
66.  
67.    private static byte[] digit(int original) {  
68.        List<Byte> list = new ArrayList<Byte>();  
69.        do {  
70.            list.add((byte) (original % 10));  
71.            original = original / 10;  
72.        }  
73.        while (original > 0);  
74.        byte[] digit = new byte[list.size()];  
75.        for (int i = 0; i < list.size(); i++) {  
76.            digit[i] = list.get(i);  
77.        }  
78.        return digit;  
79.    }  
80.}  

相关文章
|
6月前
|
数据挖掘
|
Go C++
P1001 A+B Problem
P1001 A+B Problem
111 0
|
人工智能 Java BI
|
数据库管理