📌  相关文章
📜  查找具有相同权重的最接近的整数

📅  最后修改于: 2021-05-07 08:51:28             🧑  作者: Mango

给定正整数X ,任务是找到一个整数Y ,使得:

  1. 设置的位数为Y等于X中的设置位数。
  2. X!= Y。
  3. | X – Y |最小。

例子:

方法:只需一点数学就可以将我们引向解决方案方法。由于这两个数字中的位数必须相同,因此如果将置位翻转,则也必须将未置位翻转。
现在问题减少到为翻转选择两个位。假设索引i的一位被翻转,而索引j的另一位(j 2 i – 2 j 。为了使这种情况最小化, i必须尽可能小,而j必须尽可能接近i
由于设置的位数必须相等,因此索引i上的位必须与索引j上的位不同。这意味着最小的可以是与LSB不同的最右边的位,并且j必须是下一个位。总之,正确的方法是交换不同的两个最右边的连续位。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
const int NumUnsignBits = 64;
  
// Function to return the number
// closest to x which has equal
// number of set bits as x
unsigned long findNum(unsigned long x)
{
    // Loop for each bit in x and
    // compare with the next bit
    for (int i = 0; i < NumUnsignBits - 1; i++) {
        if (((x >> i) & 1) != ((x >> (i + 1)) & 1)) {
            x ^= (1 << i) | (1 << (i + 1));
            return x;
        }
    }
}
  
// Driver code
int main()
{
    int n = 92;
  
    cout << findNum(n);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG 
{
static int NumUnsignBits = 64;
  
// Function to return the number
// closest to x which has equal
// number of set bits as x
static long findNum(long x)
{
    // Loop for each bit in x and
    // compare with the next bit
    for (int i = 0; i < NumUnsignBits - 1; i++)
    {
        if (((x >> i) & 1) != ((x >> (i + 1)) & 1))
        {
            x ^= (1 << i) | (1 << (i + 1));
            return x;
        }
    }
    return Long.MIN_VALUE;
}
  
// Driver code
public static void main(String[] args)
{
    int n = 92;
  
    System.out.println(findNum(n));
}
}
  
// This code is contributed by PrinciRaj1992


Python3
# Python3 implementation of the approach 
NumUnsignBits = 64; 
  
# Function to return the number 
# closest to x which has equal 
# number of set bits as x 
def findNum(x) : 
  
    # Loop for each bit in x and 
    # compare with the next bit 
    for i in range(NumUnsignBits - 1) :
        if (((x >> i) & 1) != ((x >> (i + 1)) & 1)) :
            x ^= (1 << i) | (1 << (i + 1)); 
            return x;
  
# Driver code 
if __name__ == "__main__" : 
    n = 92; 
    print(findNum(n)); 
  
# This code is contributed by AnkitRai01


C#
// C# implementation of the approach
using System;
      
class GFG 
{
static int NumUnsignBits = 64;
  
// Function to return the number
// closest to x which has equal
// number of set bits as x
static long findNum(long x)
{
    // Loop for each bit in x and
    // compare with the next bit
    for (int i = 0; i < NumUnsignBits - 1; i++)
    {
        if (((x >> i) & 1) != ((x >> (i + 1)) & 1))
        {
            x ^= (1 << i) | (1 << (i + 1));
            return x;
        }
    }
    return long.MinValue;
}
  
// Driver code
public static void Main(String[] args)
{
    int n = 92;
  
    Console.WriteLine(findNum(n));
}
}
  
// This code is contributed by Rajput-Ji


输出:
90

时间复杂度: O(logn)