java中實(shí)現(xiàn)遞歸計(jì)算二進(jìn)制表示中1的個(gè)數(shù)
借助Java語(yǔ)言,運(yùn)用遞歸算法計(jì)算整數(shù)N的二進(jìn)制表示中1的個(gè)數(shù)
/*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);
}
}
}
來(lái)個(gè)最簡(jiǎn)單的,不過(guò)未測(cè)試:)
public int a(int i){
if(i==0||i==1) return i;
return i%2+a(i/2);
}
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
相關(guān)文章
eclipse下整合springboot和mybatis的方法步驟
這篇文章主要介紹了eclipse下整合springboot和mybatis的方法步驟,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-03-03
ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn)
這篇文章主要介紹了ssm 使用token校驗(yàn)登錄的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
java使用正則表達(dá)校驗(yàn)手機(jī)號(hào)碼示例(手機(jī)號(hào)碼正則)
這篇文章主要介紹了java使用正則表達(dá)校驗(yàn)手機(jī)號(hào)碼示例,可校驗(yàn)三個(gè)號(hào)碼段:13*、15*、18*,大家根據(jù)自己的需要增加自己的號(hào)碼段就可以了2014-03-03
SpringBoot3整合SpringDoc實(shí)現(xiàn)在線接口文檔的詳細(xì)過(guò)程
這篇文章主要介紹了SpringBoot3整合SpringDoc實(shí)現(xiàn)在線接口文檔的詳細(xì)過(guò)程,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06
Java靜態(tài)方法不能調(diào)用非靜態(tài)成員的原因分析
在Java中,靜態(tài)方法是屬于類(lèi)的方法,而不是屬于對(duì)象的方法,它可以通過(guò)類(lèi)名直接調(diào)用,無(wú)需創(chuàng)建對(duì)象實(shí)例,非靜態(tài)成員指的是類(lèi)的實(shí)例變量和實(shí)例方法,它們需要通過(guò)對(duì)象實(shí)例才能訪問(wèn)和調(diào)用,本文小編將和大家一起探討Java靜態(tài)方法為什么不能調(diào)用非靜態(tài)成員2023-10-10
Springboot啟動(dòng)原理和自動(dòng)配置原理解析
這篇文章主要介紹了Springboot啟動(dòng)原理和自動(dòng)配置原理解析,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-04-04

