算法-第四版-练习1.3.5解答

来源:互联网 发布:自卫队 解放军 知乎 编辑:程序博客网 时间:2024/05/01 16:08

当N为50时下面这段代码会打印什么?从较高的抽象层次描述给定正整数N时这段代码的行为。

        Stack<Integer> stack = new Stack<Integer>();        while (n > 0)        {            stack.push(n % 2);            n = n / 2;        }        for (int d : stack)        {            System.out.print(d);        }        System.out.println()


n % 2得到n的二进制最低位上的值,0或者1。故上述代码就是将n的二进制位数值依次入栈,然后从栈顶将出输出,即为n的二进制表示。

测试代码:


/** * Description :  * Author      : mn@furzoom.com * Date        : Sep 28, 2016 4:12:17 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */package com.furzoom.lab.algs.ch103;/** * ClassName    : E10305 <br> * Function     : TODO ADD FUNCTION. <br> * date         : Sep 28, 2016 4:12:17 PM <br> *  * @version  */public class E10305{    public static void main(String[] args)    {        int n = 50;        Stack<Integer> stack = new Stack<Integer>();        while (n > 0)        {            stack.push(n % 2);            n = n / 2;        }        for (int d : stack)        {            System.out.print(d);        }        System.out.println();    }}
输出:

110010


算法-第四版-1.3 背包、队列和栈-习题索引汇总

算法-第四版习题索引汇总

0 0
原创粉丝点击