集册 Java实例教程 计算以整数n设置的位数。

计算以整数n设置的位数。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

433
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
计算以整数n设置的位数。


//package com.nowjava;

/*来自 
 nowjava.com - 时  代  Java*/

public class Main {

    public static void main(String[] argv) throws Exception {

        int n = 2;

        System.out.println(countBits(n));

    }


    /**

     * Counts the number of bits set in an integer <i>n</i>.

     * 

     * @param n

     *            The integer to count.

     * @return The number of bits set in n.

     */

    public static int countBits(int n) {

        int total; // Holds the number of bits set.

        for (total = 0; n != 0; ++total) {/**来自 时 代 J a
展开阅读全文