用相同的设置位数查找下一个更大的数字

编程入门 行业动态 更新时间:2024-10-23 09:37:36
本文介绍了用相同的设置位数查找下一个更大的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在解决一个给定数字n的问题,我必须找到具有相同设置位数的下一个更大的元素.在Internet上搜索时,我发现了一段有趣的代码,它只需几行代码(BIT MAGIC)此处:

I'm working on a problem where I'm given a number n, I have to find the next larger element with same number of set bits. While searching on Internet, I found an interesting piece of code which does this in few lines of code (BIT MAGIC) here:

unsigned nexthi_same_count_ones(unsigned a) { /* works for any word length */ unsigned c = (a & -a); unsigned r = a+c; return (((r ^ a) >> 2) / c) | r); }

但是我想了解有关该算法将始终有效的基本逻辑.所有边界案例将得到妥善处理.

But I want to understand the underlying logic about the algorithm that it will work always. All the boundary cases will be handled properly.

有人可以简单地解释一下逻辑吗?

Can someone please explain the logic in simple steps.

谢谢

推荐答案

在下一个更高的数字中,1的最右行中最左边的1与它的左侧的0交换位置,而剩余的1移到最右边.

In the next higher number, the leftmost 1 of the rightmost run of 1s exchanges place with the 0 to its left, while the remaining 1s move to the far right.

  • 代码隔离了最低的1
  • 将其添加到a(使纹波传递到下一个更高的0,将所有这些位取反)
  • 异或运算得到的最低有效位,向左延伸一个位置.
  • 将其向右移动两个位置,将其左边界移到原始位置的右一个位置 (从最高位置留出那个0的位置),
  • 除以最低的1可以为a的右端增加更多的0位.
  • The code isolates lowest 1,
  • adds it to a (making carries ripple through to the next higher 0, inverting all those bits)
  • The ex-or gets the least significant run of ones, extended one position to the left.
  • Shifting it right two positions takes its left boundary one position right of the original one (leaving place for that one 0 from the high position),
  • dividing by the lowest 1 makes room for as many 0-bits more as there were on the right end of a.

更多推荐

用相同的设置位数查找下一个更大的数字

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

发布评论

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

>www.elefans.com

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