欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java中实现递归计算二进制表示中1的个数

程序员文章站 2024-03-04 13:44:11
借助java语言,运用递归算法计算整数n的二进制表示中1的个数 /*use the recursive algorithme to calculate *...

借助java语言,运用递归算法计算整数n的二进制表示中1的个数

/*use the recursive algorithme to calculate 
 * the number of "1" in the binary expression
 * of an integer n.
 * note:if n is an odd, then
 * the result is the result of n/2 plus 1.
 * and the program use the bit operation to
 * improve efficency ,though it's seemingly
 * not necessary ,but the idea i think is good.
 * the program is writed by zewang zhang ,at
 * 2015-5-4,in sysu dorms.
 */
 
public class calculatenumberinbinaryexpression {
  //main method.
  public static void main(string[] args) {
     
    //for example ,make n equals 13 ,the result shows 3
    system.out.println(numofeven(13));
     
    //for example ,make n equals 128 ,the result shows 1
    system.out.println(numofeven(128));
  }
   
  //the static method of numofeven is the recursive method.
  public static int numofeven(int x) {
     
    //the base of recursive.
    if(x==0) {
      return 0;
    }
     
    //if x is an odd.
    else if(x%2!=0) {
      return numofeven(x>>1)+1;
    }
     
    //if x is an even except 0.
    else {
      while(x%2==0) {
        x=(x>>1);
      }
      return numofeven(x);
    }
  }
}

来个最简单的,不过未测试:)

public int a(int i){
    if(i==0||i==1) return i;
    return i%2+a(i/2);

}

以上所述就是本文的全部内容了,希望大家能够喜欢。