java中實現(xiàn)遞歸計算二進制表示中1的個數(shù)
更新時間:2015年05月05日 11:16:32 投稿:hebedich
這是一個很有意思的問題,是在面試中特別容易被問到的問題之一,解決這個問題第一想法肯定是一位一位的去判斷,是1計數(shù)器+1,否則不操作,跳到下一位,十分容易,編程初學者就可以做得到!
借助Java語言,運用遞歸算法計算整數(shù)N的二進制表示中1的個數(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);
}
}
}
來個最簡單的,不過未測試:)
public int a(int i){
if(i==0||i==1) return i;
return i%2+a(i/2);
}
以上所述就是本文的全部內(nèi)容了,希望大家能夠喜歡。
相關文章
eclipse下整合springboot和mybatis的方法步驟
這篇文章主要介紹了eclipse下整合springboot和mybatis的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03
SpringBoot3整合SpringDoc實現(xiàn)在線接口文檔的詳細過程
這篇文章主要介紹了SpringBoot3整合SpringDoc實現(xiàn)在線接口文檔的詳細過程,本文通過示例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2024-06-06
Java靜態(tài)方法不能調(diào)用非靜態(tài)成員的原因分析
在Java中,靜態(tài)方法是屬于類的方法,而不是屬于對象的方法,它可以通過類名直接調(diào)用,無需創(chuàng)建對象實例,非靜態(tài)成員指的是類的實例變量和實例方法,它們需要通過對象實例才能訪問和調(diào)用,本文小編將和大家一起探討Java靜態(tài)方法為什么不能調(diào)用非靜態(tài)成員2023-10-10

