国产探花免费观看_亚洲丰满少妇自慰呻吟_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);}

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 朝阳区| 沧州市| 泗水县| 九龙县| 东明县| 泰州市| 方正县| 错那县| 浙江省| 磴口县| 尉犁县| 棋牌| 沂源县| 克拉玛依市| 南木林县| 交城县| 抚松县| 玉门市| 库车县| 南华县| 中山市| 内乡县| 息烽县| 尼木县| 阳春市| 吉水县| 苗栗县| 西华县| 永川市| 聂拉木县| 增城市| 伊通| 房产| 铜山县| 乌兰察布市| 古丈县| 北票市| 德昌县| 读书| 通州区| 东乡|