C#,二进制数的非0位数统计(Bits Count)的算法与源代码

计算一个十进制数的二进制表示有多少位1?

1 遍历法(递归或非递归)

使用循环按位统计1的个数。

2 哈希查表法

利用一个数组或哈希生成一张表,存储不同二进制编码对应的值为1的二进制位数,那么在使用时,只需要去进行查询,即可在O(1)的时间复杂度内得到结果。

但是,此算法有个弊端,由于算法是采用空间换取时间的方法,当一个二进制数的位长超过一定限度时,对应的表也就会占据很大的空间,也就是说节约时间越多,花费的存储越多。另外此方法还会收到CPU缓存的限制,如果表太大,表在缓存的上下文切换也就越多,可能会导致性能没有想象中那么高。

所以,为了解决此问题,一般情况下,采用适当的二进制位长度来建表,比如8位、16位,这样情况下,可以对上述问题得到一个平衡,不仅可以享受到优越的性能,而且时间开销也没有遍历法高。

3 Variable-precision SWAR算法

在数学上,我们一般称上述问题为"计算汉明重量",而当前一直效率最好的通用算法为variable-precision SWAR算法,该算法不仅在常数时间计算多个字节的汉明重量,而且不需要使用任何额外的内存。

4 源程序

cs 复制代码
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace Legalsoft.Truffer.Algorithm
{
	public static partial class Algorithm_Gallery
	{
		public static int Count_Setbits(int n)
		{
			// initialize the result
			int bitCount = 0;
			for (int i = 1; i <= n; i++)
			{
				bitCount += Count_Setbits_Utility(i);
			}
			return bitCount;
		}

		private static int Count_Setbits_Utility(int x)
		{
			if (x <= 0)
			{
				return 0;
			}
			return (x % 2 == 0 ? 0 : 1) + Count_Setbits_Utility(x / 2);
		}

		public static int Count_Setbits_Second(int n)
		{
			int i = 0;
			int ans = 0;

			while ((1 << i) <= n)
			{
				bool k = false;

				int change = 1 << i;

				for (int j = 0; j <= n; j++)
				{
					ans += (k) ? 1 : 0;
					if (change == 1)
					{
						k = !k;
						change = 1 << i;
					}
					else
					{
						change--;
					}
				}
				i++;
			}
			return ans;
		}

		private static int Leftmost_Bit(int n)
		{
			int m = 0;
			while (n > 1)
			{
				n = n >> 1;
				m++;
			}
			return m;
		}

		private static int Next_Leftmost_Bit(int n, int m)
		{
			int temp = 1 << m;
			while (n < temp)
			{
				temp = temp >> 1;
				m--;
			}
			return m;
		}

		public static int Count_Setbits_Third(int n)
		{
			int m = Leftmost_Bit(n);

			return Count_Setbits_Third_Utility(n, m);
		}

		public static int Count_Setbits_Third_Utility(int n, int m)
		{
			if (n == 0)
			{
				return 0;
			}
			m = Next_Leftmost_Bit(n, m);

			if (n == ((int)1 << (m + 1)) - 1)
			{
				return (int)(m + 1) * (1 << m);
			}
			n = n - (1 << m);
			return (n + 1) + Count_Setbits_Third(n) + m * (1 << (m - 1));
		}
	}
}

POWER BY TRUFFER.CN

BY 315SOFT.COM

相关推荐
炽烈小老头4 分钟前
【每天学习一点算法 2025/12/30】最大子序和
学习·算法
Flash.kkl6 分钟前
优选算法专题十八——BFS解决拓扑排序
算法·宽度优先
雪雁10 分钟前
CodeSpirit 多语言国际化使用指南(Beta)
c#·asp.net·.net 10·codespirit
hetao173383711 分钟前
2025-12-30 hetao1733837 的刷题笔记
c++·笔记·算法
自己的九又四分之三站台15 分钟前
写一个简单的DebugView
c#
小袁顶风作案15 分钟前
leetcode力扣——27.移除元素、26.删除有序数组的重复项、80.删除有序数组中的重复项 II
数据结构·算法·leetcode
CreasyChan20 分钟前
C#中单个下划线的语法与用途详解
前端·c#
goodlook012327 分钟前
监控平台搭建-监控指标展示-Grafana篇(五)
java·算法·docker·grafana·prometheus
m5655bj27 分钟前
如何通过 C# 实现 PDF 页面裁剪
前端·pdf·c#
这是个栗子28 分钟前
前端开发中的常用工具函数(持续更新中...)
前端·javascript·算法