计算长位数中的置位位数

编程入门 行业动态 更新时间:2024-10-11 11:21:29
本文介绍了计算长位数中的置位位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要计算长整数中设置位的数量.另外,我需要优化相同.我正在使用以下代码:

I need to count number of set bits in a long number. Also I need to optimize the same. I'm using the following code:

public static int countSetBits(long number) { int count = 0; while (number > 0) { ++count; number &= number - 1; } return count; }

任何修改将不胜感激.

推荐答案

您可以按以下步骤编写而不加减法

You can write it without subtraction as follow

public static int countSetBits(long number) { int count = 0; while (number > 0) { count += number&1L; number>>=1L; } return count; }

如果要使用Java的内置库,则可以使用 bitCount

If You want to use Java's built-in libraries then can use bitCount

Long.bitCount(number)

如果您想查看源代码然后

public static int bitCount(long i) { i = i - ((i >>> 1) & 0x5555555555555555L); i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; i = i + (i >>> 8); i = i + (i >>> 16); i = i + (i >>> 32); return (int)i & 0x7f; }

更多推荐

计算长位数中的置位位数

本文发布于:2023-11-30 09:44:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:位数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!