java中实现递归计算二进制表示中1的个数
2015-05-05 11:16
681 查看
借助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); }
以上所述就是本文的全部内容了,希望大家能够喜欢。
您可能感兴趣的文章:
相关文章推荐
- 递归方法计算数N的二进制表示中1的个数
- 【算法数据结构Java实现】递归的简单剖析及时间复杂度计算
- 【Java】斐波那契数列(Fibonacci Sequence、兔子数列)的3种计算方法(递归实现、递归值缓存实现、循环实现、尾递归实现)
- java计算参数目录大小的递归和迭代实现
- java计算参数目录大小的递归和迭代实现
- leetcode_461. Hamming Distance 计算汉明距离,按位异或运算,计算整数的二进制表示中1的个数 java
- 一个整数二进制表示中1的个数 java实现
- 递归实现数N的二进制表示
- 算法--微软面试:整数的二进制表示中1的个数(Java实现)
- java中递归实现复制多级文件夹
- Java打印整数的二进制表示(代码与解析)
- 计算1^1+2^2+3^3+4^4+5^5+……+20^20 ,大数运算java实现
- 全排列算法-递归与字典序的实现方法(Java)
- 笔试面试算法经典--二叉树的镜像-递归与非递归实现(Java)
- 二进制中1的个数(Java实现)
- 计算机二进制数值表示为何出现原码反码补码三种方式? and 如何计算?
- java递归的简单实现方式
- 根据公式计算y的值。其中∑表示求各项的和,∏表示求各项的积。定义一个类F,实现上述功能。具体要求如下:
- java实现递归(1)
- Java实现的计算任意时间是星期几