国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java中實現遞歸計算二進制表示中1的個數

2019-11-26 15:12:22
字體:
來源:轉載
供稿:網友

借助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);}

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 称多县| 义乌市| 水富县| 吴桥县| 闸北区| 左云县| 荥经县| 宁都县| 石首市| 武强县| 甘洛县| 定襄县| 府谷县| 枣强县| 赤城县| 磐石市| 芜湖市| 桃江县| 杂多县| 四子王旗| 桐庐县| 高青县| 榆树市| 深泽县| 平谷区| 珠海市| 墨玉县| 遵化市| 志丹县| 湖南省| 洛阳市| 赞皇县| 铜陵市| 安龙县| 合肥市| 武平县| 建昌县| 北川| 江城| 朝阳市| 彩票|