题解 | #0左边必有1的二进制字符串的数量#
0左边必有1的二进制字符串的数量
http://www.nowcoder.com/practice/5a04a774b9f54d9eb783a4d583e7a60a
/*方法3:快速幂
时间复杂度O(logN)
取模的话在乘法除加上即可
* */
public static int getNum3(int n) {
if (n < 1) {
return 0;
}
if (n == 1 || n == 2) {
return n;
}
int[][] base = {{1, 1}, {1, 0}};
int[][] res = matrixPower(base, n - 2);
return 2 * res[0][0] + res[1][0];
}
//求矩阵m的p次方
public static int[][] matrixPower(int[][] m, int p) {
int[][] res = new int[m.length][m[0].length];
//先把res设为单位矩阵,相当于整数中1
for (int i = 0; i < m.length; i++) {
res[i][i] = 1;
}
int[][] tmp = m;
//求p对应的二进制
for (; p != 0; p >>= 1) {
if ((p & 1) != 0) {
res = mulMatrix(res, tmp);
}
tmp = mulMatrix(tmp, tmp);
}
return res;
}
//矩阵m1 矩阵m2相乘
public static int[][] mulMatrix(int[][] m1, int[][] m2) {
int[][] res = new int[m1.length][m2[0].length];
for (int i = 0; i < m1.length; i++) {
for (int j = 0; j < m2[0].length; j++) {
for (int k = 0; k < m2.length; k++) {
res[i][j] = res[i][j] + m1[i][k] * m2[k][j];
}
}
}
return res;
}