算法第四版习题解答(1.1 Basic Programming Model)

前言

使用的是《算法》第四版英文版,主要是习题解答。

书中jar包的导入请戳:算法(第四版)中algs4.jar下载和使用

EXERCISES

1.1.1

在这里插入图片描述

1.1.2

在这里插入图片描述

1.1.3

import java.util.Scanner;

public class Something {
   
    public static void main(String[] args) {
   
        Scanner scanner = new Scanner(System.in);
        int a = scanner.nextInt();
        int b = scanner.nextInt();
        int c = scanner.nextInt();
        if (a == b && a == c)
            System.out.println("equal");
        else
            System.out.println("not equal");
    }
}

1.1.4

a.  去掉then
b.  a > b用括号括起来
c.  true
d.  true 

1.1.5

import java.util.Scanner;

public class Something {
   
    public static void main(String[] args) {
   
        Scanner scanner = new Scanner(System.in);
        double x = scanner.nextDouble();
        double y = scanner.nextDouble();
        if ((x > 0.0 && x < 1.0) && (y > 0.0 && y < 1.0))
            System.out.println("true");
        else
            System.out.println("false");
    }
}

1.1.6

在这里插入图片描述

1.1.7

在这里插入图片描述

1.1.8

在这里插入图片描述

1.1.9

import java.util.Scanner;

// 不建议用String,因为对String对象的修改要重新创建一个String对象
// 可以好好查查资料,String、StringBuild和StringBuffer的区别
public class Something {
   
    public static void main(String[] args) {
   
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        StringBuilder sb = new StringBuilder();
        while (N > 0) {
   
            int temp = N % 2;
            N /= 2;
            sb.append(temp);
        }
        sb.reverse();
        System.out.println(sb);
    }
}

1.1.10

// 修正如下。主要是未给数组分配内存空间
int[] a =  new int[10];

1.1.11

import java.util.Scanner;

public class Something {
   
    public static void main(String[] args) {
   
        Scanner scanner = new Scanner(System.in);
        int row = scanner.nextInt();        // 二维数组的行数
        int col = scanner.nextInt();        // 二维数组的列数
        boolean[][] res = new boolean[row][col];
        for (int i = 0; i < row; i++) {
   
            for (int j = 0; j < col; j++) {
   
                res[i][j] = scanner.nextBoolean();
            }
        }
        // ============之间的为二维数组打印
        System.out.println("=============");
        for (int i = 0; i < row; i++) {
   
            for (int j = 0; j < col; j++) {
   
                if (res[i][j] == true)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            System.out.println();
        }
        System.out.println("=============");
    }
}

1.1.12

在这里插入图片描述

1.1.13

import java.util
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值