Skip to content

Commit cb86646

Browse files
committed
modify code
1 parent 35153ad commit cb86646

2 files changed

Lines changed: 25 additions & 18 deletions

File tree

src/class26/Code02_FibonacciProblem.java

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -57,24 +57,27 @@ public static int[][] matrixPower(int[][] m, int p) {
5757
int[][] t = m;// 矩阵1次方
5858
for (; p != 0; p >>= 1) {
5959
if ((p & 1) != 0) {
60-
res = muliMatrix(res, t);
60+
res = product(res, t);
6161
}
62-
t = muliMatrix(t, t);
62+
t = product(t, t);
6363
}
6464
return res;
6565
}
6666

6767
// 两个矩阵乘完之后的结果返回
68-
public static int[][] muliMatrix(int[][] m1, int[][] m2) {
69-
int[][] res = new int[m1.length][m2[0].length];
70-
for (int i = 0; i < m1.length; i++) {
71-
for (int j = 0; j < m2[0].length; j++) {
72-
for (int k = 0; k < m2.length; k++) {
73-
res[i][j] += m1[i][k] * m2[k][j];
68+
public static int[][] product(int[][] a, int[][] b) {
69+
int n = a.length;
70+
int m = b[0].length;
71+
int k = a[0].length; // a的列数同时也是b的行数
72+
int[][] ans = new int[n][m];
73+
for(int i = 0 ; i < n; i++) {
74+
for(int j = 0 ; j < m;j++) {
75+
for(int c = 0; c < k; c++) {
76+
ans[i][j] += a[i][c] * b[c][j];
7477
}
7578
}
7679
}
77-
return res;
80+
return ans;
7881
}
7982

8083
public static int s1(int n) {

src/class26/Code03_ZeroLeftOneStringNumber.java

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -78,23 +78,27 @@ public static int[][] matrixPower(int[][] m, int p) {
7878
int[][] tmp = m;
7979
for (; p != 0; p >>= 1) {
8080
if ((p & 1) != 0) {
81-
res = muliMatrix(res, tmp);
81+
res = product(res, tmp);
8282
}
83-
tmp = muliMatrix(tmp, tmp);
83+
tmp = product(tmp, tmp);
8484
}
8585
return res;
8686
}
8787

88-
public static int[][] muliMatrix(int[][] m1, int[][] m2) {
89-
int[][] res = new int[m1.length][m2[0].length];
90-
for (int i = 0; i < m1.length; i++) {
91-
for (int j = 0; j < m2[0].length; j++) {
92-
for (int k = 0; k < m2.length; k++) {
93-
res[i][j] += m1[i][k] * m2[k][j];
88+
// 两个矩阵乘完之后的结果返回
89+
public static int[][] product(int[][] a, int[][] b) {
90+
int n = a.length;
91+
int m = b[0].length;
92+
int k = a[0].length; // a的列数同时也是b的行数
93+
int[][] ans = new int[n][m];
94+
for(int i = 0 ; i < n; i++) {
95+
for(int j = 0 ; j < m;j++) {
96+
for(int c = 0; c < k; c++) {
97+
ans[i][j] += a[i][c] * b[c][j];
9498
}
9599
}
96100
}
97-
return res;
101+
return ans;
98102
}
99103

100104
public static void main(String[] args) {

0 commit comments

Comments
 (0)