最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

计算长位数中的置位位数

SEO心得admin39浏览0评论
本文介绍了计算长位数中的置位位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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; }
发布评论

评论列表(0)

  1. 暂无评论