M-ésimo número más pequeño que tiene k número de bits establecidos.

Dados dos enteros no negativos m y k . El problema es encontrar el m-ésimo número más pequeño que tenga k número de bits establecidos.
Restricciones: 1 <= m, k.
Ejemplos: 
 

Input : m = 4, k = 2
Output : 9
(9)10 = (1001)2, it is the 4th smallest
number having 2 set bits.


Input : m = 6, k = 4
Output : 39

Enfoque: Los siguientes son los pasos:
 

  1. Encuentre el número más pequeño que tenga k número de bits establecidos. Sea num , donde num = (1 << k) – 1.
  2. Repita m-1 veces y cada vez reemplace num con el siguiente número más alto que ‘num’ que tenga el mismo número de bits que en ‘num’. Consulte esta publicación para encontrar el siguiente número superior requerido.
  3. Finalmente devuelve num .

C++

// C++ implementation to find the mth smallest
// number having k number of set bits
#include <bits/stdc++.h>
using namespace std;
 
typedef unsigned int uint_t;
 
// function to find the next higher number
// with same number of set bits as in 'x'
uint_t nxtHighWithNumOfSetBits(uint_t x)
{
    uint_t rightOne;
    uint_t nextHigherOneBit;
    uint_t rightOnesPattern;
 
    uint_t next = 0;
 
    /* the approach is same as discussed in
       https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
    */
    if (x) {
        rightOne = x & -(signed)x;
 
        nextHigherOneBit = x + rightOne;
 
        rightOnesPattern = x ^ nextHigherOneBit;
 
        rightOnesPattern = (rightOnesPattern) / rightOne;
 
        rightOnesPattern >>= 2;
 
        next = nextHigherOneBit | rightOnesPattern;
    }
 
    return next;
}
 
// function to find the mth smallest number
// having k number of set bits
int mthSmallestWithKSetBits(uint_t m, uint_t k)
{
    // smallest number having 'k'
    // number of set bits
    uint_t num = (1 << k) - 1;
 
    // finding the mth smallest number
    // having k set bits
    for (int i = 1; i < m; i++)
        num = nxtHighWithNumOfSetBits(num);
 
    // required number
    return num;
}
 
// Driver program to test above
int main()
{
    uint_t m = 6, k = 4;
    cout << mthSmallestWithKSetBits(m, k);
    return 0;
}

Java

// Hava implementation to find the mth
// smallest number having k number of set bits
 
import java.util.*;
 
class GFG
{
 
  // function to find the next higher number
  // with same number of set bits as in 'x'
  static int nxtHighWithNumOfSetBits(int x)
  {
    int rightOne = 0;
    int nextHigherOneBit = 0;
    int rightOnesPattern = 0;
 
    int next = 0;
 
    if (x > 0) {
      rightOne = x & (-x);
      nextHigherOneBit = x + rightOne;
 
      rightOnesPattern = x ^ nextHigherOneBit;
 
      rightOnesPattern
        = (rightOnesPattern / rightOne);
 
      rightOnesPattern >>= 2;
 
      next = nextHigherOneBit | rightOnesPattern;
    }
 
    return next;
  }
 
  // function to find the mth smallest
  // number having k number of set bits
  static int mthSmallestWithKSetBits(int m, int k)
  {
    // smallest number having 'k'
    // number of set bits
    int num = (1 << k) - 1;
 
    // finding the mth smallest number
    // having k set bits
    for (int i = 1; i < m; i++)
      num = nxtHighWithNumOfSetBits(num);
 
    // required number
    return num;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    int m = 6;
    int k = 4;
 
    // Function call
    System.out.println(mthSmallestWithKSetBits(m, k));
  }
}
 
// This code is contributed by phasing17

Python3

# Python3 implementation to find the mth
# smallest number having k number of set bits
 
# function to find the next higher number
# with same number of set bits as in 'x'
 
 
def nxtHighWithNumOfSetBits(x):
    rightOne = 0
    nextHigherOneBit = 0
    rightOnesPattern = 0
 
    next = 0
 
    """ the approach is same as discussed in
    http:#www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
    """
    if (x):
        rightOne = x & (-x)
        nextHigherOneBit = x + rightOne
 
        rightOnesPattern = x ^ nextHigherOneBit
 
        rightOnesPattern = (rightOnesPattern) // rightOne
 
        rightOnesPattern >>= 2
 
        next = nextHigherOneBit | rightOnesPattern
 
    return next
 
# function to find the mth smallest
# number having k number of set bits
 
 
def mthSmallestWithKSetBits(m, k):
 
    # smallest number having 'k'
    # number of set bits
    num = (1 << k) - 1
 
    # finding the mth smallest number
    # having k set bits
    for i in range(1, m):
        num = nxtHighWithNumOfSetBits(num)
 
    # required number
    return num
 
 
# Driver Code
if __name__ == '__main__':
    m = 6
    k = 4
    print(mthSmallestWithKSetBits(m, k))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)

C#

// C# implementation to find the mth
// smallest number having k number of set bits
using System;
 
class GFG {
    // function to find the next higher number
    // with same number of set bits as in 'x'
    static int nxtHighWithNumOfSetBits(int x)
    {
        int rightOne = 0;
        int nextHigherOneBit = 0;
        int rightOnesPattern = 0;
 
        int next = 0;
 
        if (x > 0) {
            rightOne = x & (-x);
            nextHigherOneBit = x + rightOne;
 
            rightOnesPattern = x ^ nextHigherOneBit;
 
            rightOnesPattern
                = (rightOnesPattern / rightOne);
 
            rightOnesPattern >>= 2;
 
            next = nextHigherOneBit | rightOnesPattern;
        }
 
        return next;
    }
 
    // function to find the mth smallest
    // number having k number of set bits
    static int mthSmallestWithKSetBits(int m, int k)
    {
        // smallest number having 'k'
        // number of set bits
        int num = (1 << k) - 1;
 
        // finding the mth smallest number
        // having k set bits
        for (int i = 1; i < m; i++)
            num = nxtHighWithNumOfSetBits(num);
 
        // required number
        return num;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
 
        int m = 6;
        int k = 4;
 
        // Function call
        Console.Write(mthSmallestWithKSetBits(m, k));
    }
}
 
// This code is contributed by phasing17

Javascript

//JS implementation to find the mth
// smallest number having k number of set bits
 
// function to find the next higher number
// with same number of set bits as in 'x'
function nxtHighWithNumOfSetBits(x)
{
    var rightOne = 0;
    var nextHigherOneBit = 0;
    var rightOnesPattern = 0;
 
    var next = 0;
 
    if (x > 0)
    {
        rightOne = x & (-x);
        nextHigherOneBit = x + rightOne;
 
        rightOnesPattern = x ^ nextHigherOneBit;
 
        rightOnesPattern = Math.floor((rightOnesPattern) / rightOne);
 
        rightOnesPattern >>= 2;
 
        next = nextHigherOneBit | rightOnesPattern;
    }
 
    return next;
}
 
// function to find the mth smallest
// number having k number of set bits
function mthSmallestWithKSetBits(m, k)
{
    // smallest number having 'k'
    // number of set bits
    var num = (1 << k) - 1;
 
    // finding the mth smallest number
    // having k set bits
    for (var i = 1; i < m; i++)
        num = nxtHighWithNumOfSetBits(num);
 
    // required number
    return num;
}
 
// Driver Code
var m = 6;
var k = 4;
 
//Function call
console.log(mthSmallestWithKSetBits(m, k));
 
// This code is contributed by phasing17

Producción: 
 

39

Complejidad del tiempo: O(m)

Complejidad espacial: O(1)
Este artículo es una contribución de Ayush Jauhari . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *