算法(第四版)-算法练习(2)-(1.1.8-1.1.14)-kotlin

本系列博客的习题都来自《算法(第四版)》,如果有其他人也在看这本书,欢迎来评论区多多交流

 

包含的知识点

  • java的基本语法
  • 进制转换
  • 一维数组逆序输出
  • 二维数组的转置(交换行与列)

1.1.8 下列语句会打印出什么结果?给出解释。

a. System.out.println('b');

b. System.out.println('b' + 'c');

c. System.out.println((char) ('a' + 4));


    //1.1.8 给出以下表达式的值:
    @Test
    fun test1_1_8() {
        println('b')
        println('b'.toInt() + 'c'.toInt())
        println(('a' + 4))
    }

其中,b的ASCII码为98,c的为99

​​​​​​​答案:

Connected to the target VM, address: '127.0.0.1:50867', transport: 'socket'
b
197
e
Disconnected from the target VM, address: '127.0.0.1:50867', transport: 'socket'

 1.1.9 编写一段代码,将一个正整数 N 用二进制表示并转换为一个 String 类型的值 s

答案

    @Test
    fun test1_1_9(){
        test1_1_9(35)
    }

    private fun test1_1_9(N:Int){
        var s = ""
        var n = N
        while (n > 0) {
            s = (n % 2).toString() + s
            n /= 2
        }
        println("$N 对应的二进制字符串=$s")
    }

以上代码相对简洁,但效率不怎么样,Java源码的的实现效率可以

源码答案

    public static String toBinaryString(int i) {
        return toUnsignedString0(i, 1);
    }

    private static String toUnsignedString0(int val, int shift) {
        // assert shift > 0 && shift <=5 : "Illegal shift value";
        int mag = Integer.SIZE - Integer.numberOfLeadingZeros(val);
        int chars = Math.max(((mag + (shift - 1)) / shift), 1);
        char[] buf = new char[chars];

        formatUnsignedInt(val, shift, buf, 0, chars);

        // Android-changed: Use regular constructor instead of one which takes over "buf".
        // return new String(buf, true);
        return new String(buf);
    }

1.1.10 下面这段代码有什么问题?

int[] a;
for (int i = 0; i < 10; i++)
   a[i] = i * i;​​​​​​​

解答:它没有用 new 为 a[] 分配内存。这段代码会产生一个 variable a might not have been initialized 的编译错误。

1.1.11 编写一段代码,打印出一个二维布尔数组的内容。其中,使用 * 表示真,空格表示假。打印出行号和列号。

    @Test
    fun test1_1_11() {
        test1_1_11(
            arrayOf(
                arrayOf(true, false, false, true, true, true),
                arrayOf(false, false, true, true, false, false)
            )
        )
    }

    private fun test1_1_11(array: Array<Array<Boolean>>) {
        for (i in array.indices) {
            for (j in array[i].indices) {
                val suffix = if (array[i][j]) {
                    "*"
                } else {
                    "/"
                }
                println(String.format(Locale.CHINA, "%d  %d $suffix", i + 1, j + 1))
            }
        }
    }

 1.1.12 以下代码段会打印出什么结果?

int[] a = new int[10];
for (int i = 0; i < 10; i++)
   a[i] = 9 - i;
for (int i = 0; i < 10; i++)
   a[i] = a[a[i]];
for (int i = 0; i < 10; i++)
   System.out.println(a[i]); 

/**网上看到的PDF电子书的最后一句都有误,是        
System.out.println(i);
但应该是System.out.println(a[i]);所以这里改掉了
**/

    @Test
    fun test1_1_12() {
        val a = IntArray(10)
        for (i in 0..9) {
            a[i] = 9 - i
        }
        //int[] a ={9,8,7,6,5,4,3,2,1,0}
        for (i in 0..9) {
            a[i] = a[a[i]]
        }
        //int[] a ={0,1,2,3,4,4,3,2,1,0}
        for (i in 0..9) {
            println(a[i])
        }
    }

 答案:

​​​​​​​

1.1.13 编写一段代码,打印出一个 M 行 N 列的二维数组的转置(交换行和列)。 

 

    @Test
    fun test1_1_13() {
        test1_1_13(arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6)))
    }

    private fun test1_1_13(array: Array<Array<Int>>) {
        val temp = Array(array[0].size, init = { row ->
            Array(array.size, init = { column ->
                val value = array[column][row]
                print("$value ")
                if (column == array.size - 1) {
                    print("\n")
                }
                value
            })
        })
    }

答案:

 

1.1.14 编写一个静态方法 lg(),接受一个整型参数 N,返回不大于 log2N 的最大整数。不要使用 Math 库。

    @Test
    fun test1_1_14(){
        test1_1_14(5)
        test1_1_14(29)
        test1_1_14(131)
    }

    private fun test1_1_14(N: Int) {
        if (N < 1) {
            println("整数N 小于 1,不大于 log2N 的最大整数 结果不存在")
            return
        }
        //第一种
        var total = N
        var num = 0
        while (total / 2 > 0) {
            num++
            total /= 2
        }
        //第二种
//        var total = 1
//        var num = -1
//        while (total <= N) {
//            num++
//            total *= 2
//        }
        println("整数N=$N 对应的 不大于 log2N 的最大整数=$num")
    }

 答案:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值