Returns amount of binary digits places if given integer n - Java java.lang

Java examples for java.lang:int Binary

Description

Returns amount of binary digits places if given integer n

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        int n = 2;
        System.out.println(getBinaryDigits(n));
    }/*from  ww w.  ja v  a2s.  co m*/

    /**
     * Returns amount of binary digits places if given integer n 
     * @param n 
     * @return number of binary digit places. ie, given n = 13, binary = 1101, 
     * number of binary places = 4 
     */
    public static int getBinaryDigits(int n) {
        if (n == 0 || n == 1)
            return 1;

        int k = 0;
        while (n - (1 << k) >= 0) {
            k++;
        }

        return k;
    }
}

Related Tutorials