📜  查找下一个稀疏编号

📅  最后修改于: 2021-04-26 05:52:11             🧑  作者: Mango

如果数字的二进制表示形式中没有两个相邻的1,则该数字为稀疏。例如,5(二进制表示:101)是稀疏的,但是6(二进制表示:110)不是稀疏的。
给定数字x,找到大于或等于x的最小稀疏数。

例子:

Input: x = 6
Output: Next Sparse Number is 8

Input: x = 4
Output: Next Sparse Number is 4

Input: x = 38
Output: Next Sparse Number is 40

Input: x = 44
Output: Next Sparse Number is 64

我们强烈建议您单击此处并进行实践,然后再继续解决方案。

一个简单的解决方案是执行以下操作:

1) Write a utility function isSparse(x) that takes a number 
   and returns true if x is sparse, else false.  This function
   can be easily written by traversing the bits of input number.
2) Start from x and do following 
   while(1)
   {
      if (isSparse(x))
         return x;
      else 
         x++
   }

isSparse()的时间复杂度为O(Log x)。该解决方案的时间复杂度为O(x Log x)。下一个稀疏数最多可以相距O(x)距离。

感谢kk_angel建议上述解决方案。

一个有效的解决方案可以解决此问题,而无需一个个地检查所有数字。以下是步骤。

1) Find binary of the given number and store it in a 
   boolean array.
2) Initialize last_finalized bit position as 0.
2) Start traversing the binary from least significant bit.
    a) If we get two adjacent 1's such that next (or third) 
       bit is not 1, then 
          (i)  Make all bits after this 1 to last finalized
               bit (including last finalized) as 0. 
          (ii) Update last finalized bit as next bit. 

例如,假设二进制表示为010100010 11 101,我们将其更改为01010001 100000 (突出显示11之后的所有位均设置为0)。再次两个1相邻,因此将二进制表示更改为010100 10000000 。这是我们的最终答案。

下面是上述解决方案的实现。

C++
// C++ program to find next sparse number
#include
using namespace std;
  
int nextSparse(int x)
{
    // Find binary representation of x and store it in bin[].
    // bin[0] contains least significant bit (LSB), next
    // bit is in bin[1], and so on.
    vector bin;
    while (x != 0)
    {
        bin.push_back(x&1);
        x >>= 1;
    }
  
    // There my be extra bit in result, so add one extra bit
    bin.push_back(0);
    int n = bin.size();  // Size of binary representation
  
    // The position till which all bits are finalized
    int last_final = 0;
  
    // Start from second bit (next to LSB)
    for (int i=1; i=last_final; j--)
                bin[j] = 0;
  
            // Store position of the bit set so that this bit
            // and bits before it are not changed next time.
            last_final = i+1;
        }
    }
  
    // Find decimal equivalent of modified bin[]
    int ans = 0;
    for (int i =0; i


Java
// Java program to find next sparse number 
import java.util.*; 
  
class GFG{
static int nextSparse(int x) 
{ 
    // Find binary representation of x and store it in bin.get(]. 
    // bin.get(0] contains least significant bit (LSB), next 
    // bit is in bin.get(1], and so on. 
    ArrayList bin = new ArrayList(); 
    while (x != 0) 
    { 
        bin.add(x&1); 
        x >>= 1; 
    } 
  
    // There my be extra bit in result, so add one extra bit 
    bin.add(0); 
    int n = bin.size(); // Size of binary representation 
  
    // The position till which all bits are finalized 
    int last_final = 0; 
  
    // Start from second bit (next to LSB) 
    for (int i=1; i=last_final; j--) 
                bin.set(j,0); 
  
            // Store position of the bit set so that this bit 
            // and bits before it are not changed next time. 
            last_final = i+1; 
        } 
    } 
  
    // Find decimal equivalent of modified bin.get(] 
    int ans = 0; 
    for (int i =0; i


Python3
# Python3 program to find next 
# sparse number 
  
def nextSparse(x):
      
    # Find binary representation of 
    # x and store it in bin[]. 
    # bin[0] contains least significant 
    # bit (LSB), next bit is in bin[1], 
    # and so on. 
    bin = [] 
    while (x != 0):
        bin.append(x & 1) 
        x >>= 1
  
    # There my be extra bit in result, 
    # so add one extra bit 
    bin.append(0) 
    n = len(bin) # Size of binary representation 
      
    # The position till which all 
    # bits are finalized 
    last_final = 0
  
    # Start from second bit (next to LSB) 
    for i in range(1,n - 1):
          
        # If current bit and its previous 
        # bit are 1, but next bit is not 1.
        if ((bin[i] == 1 and bin[i - 1] == 1 
            and bin[i + 1] != 1)):
                  
            # Make the next bit 1
            bin[i + 1] = 1 
              
            # Make all bits before current
            # bit as 0 to make sure that 
            # we get the smallest next number 
            for j in range(i,last_final-1,-1):
                bin[j] = 0
              
            # Store position of the bit set
            # so that this bit and bits
            # before it are not changed next time.
            last_final = i + 1 
  
    # Find decimal equivalent 
    # of modified bin[] 
    ans = 0 
    for i in range(n): 
        ans += bin[i] * (1 << i) 
    return ans 
  
# Driver Code
if __name__=='__main__':
    x = 38 
    print("Next Sparse Number is",nextSparse(x)) 
  
# This code is contributed by 
# mits


C#
// C# program to find next sparse number 
using System;
using System.Collections;
  
  
class GFG{
static int nextSparse(int x) 
{ 
    // Find binary representation of x and store it in bin.get(]. 
    // bin.get(0] contains least significant bit (LSB), next 
    // bit is in bin.get(1], and so on. 
    ArrayList bin = new ArrayList(); 
    while (x != 0) 
    { 
        bin.Add(x&1); 
        x >>= 1; 
    } 
  
    // There my be extra bit in result, so add one extra bit 
    bin.Add(0); 
    int n = bin.Count; // Size of binary representation 
  
    // The position till which all bits are finalized 
    int last_final = 0; 
  
    // Start from second bit (next to LSB) 
    for (int i = 1; i < n-1; i++) 
    { 
    // If current bit and its previous bit are 1, but next 
    // bit is not 1. 
    if ((int)bin[i] == 1 && (int)bin[i-1] == 1 && (int)bin[i+1] != 1) 
    { 
            // Make the next bit 1 
            bin[i+1]=1; 
  
            // Make all bits before current bit as 0 to make 
            // sure that we get the smallest next number 
            for (int j = i; j >= last_final; j--) 
                bin[j]=0; 
  
            // Store position of the bit set so that this bit 
            // and bits before it are not changed next time. 
            last_final = i + 1; 
        } 
    } 
  
    // Find decimal equivalent of modified bin.get(] 
    int ans = 0; 
    for (int i = 0; i < n; i++) 
        ans += (int)bin[i]*(1<


PHP
>= 1;
    }
  
    // There my be extra bit in result,
    // so add one extra bit
    array_push($bin, 0);
    $n = count($bin); // Size of binary representation
      
    // The position till which all 
    // bits are finalized
    $last_final = 0;
  
    // Start from second bit (next to LSB)
    for ($i = 1; $i < $n - 1; $i++)
    {
    // If current bit and its previous 
    // bit are 1, but next bit is not 1.
    if ($bin[$i] == 1 && 
        $bin[$i - 1] == 1 && 
        $bin[$i + 1] != 1)
    {
        // Make the next bit 1
        $bin[$i + 1] = 1;
  
        // Make all bits before current 
        // bit as 0 to make sure that 
        // we get the smallest next number
        for ($j = $i; $j >= $last_final; $j--)
            $bin[$j] = 0;
  
        // Store position of the bit set 
        // so that this bit and bits 
        // before it are not changed next time.
        $last_final = $i + 1;
    }
    }
  
    // Find decimal equivalent
    // of modified bin[]
    $ans = 0;
    for ($i = 0; $i < $n; $i++)
        $ans += $bin[$i] * (1 << $i);
    return $ans;
}
  
// Driver Code
$x = 38;
echo "Next Sparse Number is " . 
                nextSparse($x);
  
// This code is contributed by mits
?>


输出:

Next Sparse Number is 40

该解决方案的时间复杂度为O(Log x)。

感谢gccode建议上述解决方案。