算法4 自我练习

算法4笔记 Chapter 1

目前正在学习中,程序写的不是很对,有错的地方欢迎大家指正。

1.1.3 编写一个程序,从命令行得到三个整数参数。如果它们都相等则打印equal,否则打印not equal
public class isequal{
    public static void main(String[] args){
        int a = Integer.parseInt(arg[0]);
        int b = Integer.parseInt(arg[1]);
        int c = Integer.parseInt(arg[2]);
        String caution = "equal";
        if(a!=b){
            caution = "Not equal";
        }
        if(b!=c){
            caution = "Not equal";
        }
}
}
1.1.5编写一段程序,如果double类型的变量x和y都严格位于0与1之间则打印true,否则打印false。
public class Randomequal{
    public static double Randomequal(double x,double y){
        if(x>0&&x<1&&y>9&&y<1){
            return 1.0; 
        }
        else{
        return -1.0;
        }
}
    public static void main(String[] args){
    double x = StdIn.Random();
    double y = StdIn.Random();
    String caution = "true";
    if(Randomqual(x,y)==1){
        caution = "true";
    }
    else{
        caution = "false";
    }
    StdOut.println(caution);
    }
}
1.1.9编写一段代码,将一个正整数N用二进制表示并转换为一个String类型的值s。
public class BinaryString{//迭代版
    public static String BinaryString(String s){
        //对于负数怎么办?
        String s = "";
        int N = StdIn.readInt();
        for(int i = N;N > 0;N /= 2){
            s = (N % 2) + s;
            }
        return s;
    }
}
public class BinaryString{//递归版
    public static String Binary(int s){
        if(s==0) return s;
        else return Binary(s/2);
        System.Out.println("%d",s%2);
    }
}
1.1.13编写一段代码,将M行N列的矩阵转置。
public class Transform{
    public static int[] Transform(int[][]a,int[][]b){
        for(int i = 0;i < a.length;i++)
            for(int j = 0;j<a.length;i++)
                b[i][j] = a[j][i];
        }
    return b;
}
1.1.14编写一个静态方法lg(),接受一个整形参数N,返回不大于logN的最大整数。
public class math.log{
    public static int lg(int N){
        int a = 1;
        int b = 0;
        for(b;a <= N;b++)
            a *= 2;
        }
        return b-1;
}
1.1.15 编写一个静态方法histogram(),接受一个整形数组a[]和一个整数M为参数并返回一个大小为M的数组,其中第i个元素的值为整数i在参数数组中出现的次数。如果a[]中值均在0到M之间,返回数组中所有元素纸盒应该和a.length相等。
public class Histogram{
    public static int[] histogram(int[] a,M){
        int c = 0;
        int[] b = new int[M];
        for(int i = 0;i < a.length; i++)
            for(int j = 0;j<a.length; j++)
                if(i==a[j]) c++;
                b[j]=c;
        return b;
    }
}
1.1.20 编写一个递归的静态方法计算ln(N!)的值。
public class LnN{
    public static int ln(int N){
    //ln(N!)=ln1+ln2+...lnN
        if(N>1) return ln(N-1);
        else return N;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值