计算长整数中的置位位数

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

此问题已在此处得到了回答.

This question has been answered here.

我的查询是,按照方法1起作用,但是它的变化,即方法2无效,而是给出了预期输出值的两倍.我不知道为什么.

My query is, following approach-1 works, however the variation of it, that is approach-2 does not, rather it gives double the value of expected output. I can not find out why.

方法1

public class Solution { public int numSetBits(long a) { int count = 0; long temp = 0; for(int i = 0 ; i < 64 ; i++) { // 64-bit for long data-type temp = 1; temp = temp << i; temp = a & temp; if((temp > 0)) count++; } return count; } }

方法2

public class Solution { public int numSetBits(long a) { int count=0; for(int i=0; i<64; i++) { if((a & (1 << i))>0) count++; } return count; } }

推荐答案

第二种方法失败,因为1 << i的结果是int,而不是long.因此,位掩码回绕了,因此a的低32位被扫描了两次,而a的高32位被忽略了.

The second approach fails because the result of 1 << i is an int, not a long. So the bit mask wraps around, and so the lower 32 bits of a get scanned twice, while the higher 32 bits of a are left uncounted.

因此,当i达到值32时,(1 << i)不会是2 32 ,而是2 0 (即1),与当i为0时.类似地,当i为33时,(1 << i)不会是2 33 ,而是2 1 ,...等等.

So, when i reaches the value 32, (1 << i) will not be 232, but 20 (i.e. 1), which is the same as when i was 0. Similarly when i is 33, (1 << i) will not be 233, but 21, ...etc.

通过将常数1设为long来纠正此问题:

Correct this by making the constant 1 a long:

(1L << i)

更多推荐

计算长整数中的置位位数

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

发布评论

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

>www.elefans.com

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