给定无符号数,请使用给定无符号数的位找到可以形成的最小数。
例子 :
Input : 6
Output : 3
Binary representation of 6 is 0000….0110. Smallest number with same number of set bits 0000….0011.
Input : 11
Output : 7
简单方法:
1.使用简单的十进制到二进制表示技术查找数字的二进制表示形式。
2.计数二进制表示中等于“ n”的置位位数。
3.创建一个将“ n”个最低有效位设置为1的二进制表示形式。
4.将二进制表示形式转换回数字。
高效方法:
1.只需测量数字的位表示形式中存在的1的数量即可。
2.(设置位的数量提高到2的幂)– 1表示最小数量。
C++
// An efficient C++ program to find
// minimum number formed by bits of a given number.
#include
#define ll unsigned int
using namespace std;
// Returns minimum number formed by
// bits of a given number.
ll minimize(ll a)
{
// _popcnt32(a) gives number of 1's
// present in binary representation
// of a.
ll n = _popcnt32(a);
return (pow(2, n) - 1);
}
// Driver function.
int main()
{
ll a = 11;
cout << minimize(a) << endl;
return 0;
}
Java
// An efficient Java program to
// find minimum number formed
// by bits of a given number.
import java.io.*;
class GFG
{
public static int _popcnt32(long number)
{
int count = 0;
while (number > 0)
{
count += number & 1L;
number >>= 1L;
}
return count;
}
// Returns minimum number formed
// by bits of a given number.
static long minimize(long a)
{
// _popcnt32(a) gives number
// of 1's present in binary
// representation of a.
int n = _popcnt32(a);
return ((long)Math.pow(2, n) - 1);
}
// Driver Code.
public static void main(String args[])
{
long a = 11;
System.out.print(minimize(a));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Python3
# An efficient Python3 program
# to find minimum number formed
# by bits of a given number.
# Returns minimum number formed by
# bits of a given number.
def minimize(a):
# _popcnt32(a) gives number of 1's
# present in binary representation
# of a.
n = bin(a).count("1")
return (pow(2, n) - 1)
# Driver Code
a = 11
print(minimize(a))
# This code is contributed by Mohit Kumar
C#
// An efficient C# program to
// find minimum number formed
// by bits of a given number.
using System;
using System.Linq;
using System.Collections.Generic;
class GFG
{
// Returns minimum number formed
// by bits of a given number.
static long minimize(long a)
{
// _popcnt32(a) gives number
// of 1's present in binary
// representation of a.
string binaryString = Convert.ToString(a, 2);
int n = binaryString.Split(new [] {'0'},
StringSplitOptions.RemoveEmptyEntries).Length + 1;
return ((long)Math.Pow(2, n) - 1);
}
// Driver Code.
static void Main()
{
long a = 11;
Console.Write(minimize(a));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
输出 :
7
注意:上面的代码使用GCC特定的功能。如果我们希望为其他编译器编写代码,则可以使用整数形式的Count设置位。