当前位置:编程学习 > JAVA >>

一道简单的JAVA踢,请各位大神为新手的我解决一下

public class BetterProgrammerTask {

    public static int getRequiredNumberOfBits(int N) {
        /*
          Please implement this method to
          return the number of bits which is just enough to store any integer from 0 to N-1 inclusively
          for any int N > 0
          Example: to store 5 integers from 0 to 4 you need 3 bits: 000, 001, 010, 011, 100 and 101
        */
    }
} java bit --------------------编程问答--------------------

    public static int getRequiredNumberOfBits(int N) {
         /*
           Please implement this method to
           return the number of bits which is just enough to store any integer from 0 to N-1 inclusively
           for any int N > 0
           Example: to store 5 integers from 0 to 4 you need 3 bits: 000, 001, 010, 011, 100 and 101
         */
    
     String str = "";
     if(N>0){
     str = Integer.toBinaryString(N);
     }
    
     return str.length();
     }
--------------------编程问答-------------------- 这题的意思你可以解释一下给我听么?我还没搞懂题目意思 --------------------编程问答-------------------- 你自己不是实现了么,还想问什么 --------------------编程问答-------------------- --------------------编程问答-------------------- public static int getRequiredNumberOfBits(int n){
/*
 Please implement this method to
 return the number of bits which is just enough to store any integer from 0 to N-1 inclusively
 for any int N > 0
 Example: to store 5 integers from 0 to 4 you need 3 bits: 000, 001, 010, 011, 100 and 101
*/
    n = n-1;   
int count = 0;
do {
count++;
n >>>= 1;
} while (n > 0);
return count;

} --------------------编程问答-------------------- --------------------编程问答-------------------- 就是把n转化成2进制 然后求这个2进制的长度  代码参照一楼
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,