【<算法>从零开始】20190715-2

220 阅读1分钟

虽然java中有Integer.toBinaryString()方法将正整数转化成String类型的二进制。

但《算法》中提供了非常精巧的一个方法。

感受到了智商碾压。

正整数N转化。

String s="";
for (n=N;n>0;n/=2){
    s=(n%2)+s;
}

用了一个巧妙的for循环,并且使用的是

+s
而不是
s+=
巧妙地完成了将余数倒序的效果

算法练习1.1.13

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

    int[][] mat = {{1, 2, 3}, {2, 3, 4}};
    int m = mat.length;
    int n = mat[0].length;
    int[][] tran = new int[n][m];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            tran[j][i] = mat[i][j];

        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            System.out.print(tran[i][j]);
            }
        }
    }
}

练习1.1.14

public class main {
public static void main(String[] args) {
    int N = 200;
    System.out.print(lg(N));

}

public static int lg(int N) {
    int k = 0;
    int m=1;
    while(m<N){
        k++;
        m=power((k+1));
    }
    return k;
}
public static int power(int k){
    int m=1;
    for (int i=0;i<k;i++){
        m*=2;
    }
    return m;
    }
}

不许使用Math库,对对数运算进行变换,这样就用最基础的迭代实现。