java中實(shí)現(xiàn)遞歸計(jì)算二進(jìn)制表示中1的個(gè)數(shù)
更新時(shí)間:2015年05月05日 11:16:32 投稿:hebedich
這是一個(gè)很有意思的問題,是在面試中特別容易被問到的問題之一,解決這個(gè)問題第一想法肯定是一位一位的去判斷,是1計(jì)數(shù)器+1,否則不操作,跳到下一位,十分容易,編程初學(xué)者就可以做得到!
借助Java語言,運(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); } } }
來個(gè)最簡(jiǎn)單的,不過未測(cè)試:)
public int a(int i){ if(i==0||i==1) return i; return i%2+a(i/2); }
以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。
相關(guān)文章
Mybatis中注入執(zhí)行sql查詢、更新、新增及建表語句案例代碼
這篇文章主要介紹了Mybatis中注入執(zhí)行sql查詢、更新、新增以及建表語句,主要說明一個(gè)另類的操作,注入sql,并使用mybatis執(zhí)行,結(jié)合案例代碼詳解講解,需要的朋友可以參考下2023-02-02SpringBoot利用@Retryable注解實(shí)現(xiàn)接口重試
本文主要介紹了springboot如何利用@Retryable注解實(shí)現(xiàn)接口重試功能,文中示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06SpringBoot整合Ldap的實(shí)現(xiàn)示例
本文主要介紹了SpringBoot整合Ldap的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11alibaba?seata服務(wù)端具體實(shí)現(xiàn)
seata是來處理分布式服務(wù)之間互相調(diào)用的事務(wù)問題,本文重點(diǎn)給大家介紹alibaba-seata實(shí)現(xiàn)方法,文中通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-02-02詳解Java實(shí)現(xiàn)負(fù)載均衡的幾種算法代碼
本篇文章主要介紹了詳解Java實(shí)現(xiàn)負(fù)載均衡的幾種算法代碼 ,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-02-02