对于整数N,存在范围从0到N-1的元素。某些元素可以转换为其他元素。对于每个转换,每个转换都需要一定的工作量,即等于1个单位。当且仅当A!= B并且A&B = A(其中&是按位AND运算符)时,元素A才能转换为元素B。我们需要通过一系列转换,从值为0的元素中获取值为X的元素,以寻求最大的努力。
例子 :
Input : X = 2
Output : 1
The only way of obtaining 2 is to directly transform 0 to 2 (bitwise AND of 0 and 2 is 0) and hence requires one step.
Input : X = 3
Output : 2
3 can be obtained in two steps. First, transform 0 to 1 (bitwise AND of 0 and 1 is 0). Then, transform 1 to 3 (bitwise AND of 1 and 3 is 1).
一种简单的解决方案是计算X中设置的位数。
解释:
首先,考虑从A到B的单步转换。A的所有设置位(等于1的位)都应在B中设置,否则A和B的按位与将不等于A。在A中设置但在B中未设置的位,则无法进行转换。 A的未设置位可以在B中设置或取消设置,这无关紧要。然后,我们可以通过一步设置A中的所有未设置位,将A更改为B。因此,如果我们必须至少将0转换为X,答案将是1,因为0与任意数字的按位AND均为0。
但是我们必须计算最大步数。因此,在每个步骤中,我们从右开始设置每个位,并且一旦设置后就无法清除该设置位。
例子:
假设我们要从0获得13(二进制1101)。首先,通过将0转换为1(二进制0001),从右开始设置第1位。接下来,我们从右边开始将第3位设置为5(二进制0101)。最后一步是设置第4位并获得13(1101)。
C++
// CPP code to find the maximum possible
// effort
#include
using namespace std;
// Function to get no of set bits in binary
// representation of positive integer n
unsigned int countSetBits(unsigned int n)
{
unsigned int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}
// Driver code
int main()
{
int i = 3;
cout << countSetBits(i);
return 0;
}
Java
// Java code to find the maximum
// possible effort
class GFG {
// Function to get no. of
// set bits in binary
// representation of
// positive integer n
static int countSetBits(int n)
{
int count = 0;
while (n != 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
// Driver code
public static void main(String[] args)
{
int i = 3;
System.out.print(countSetBits(i));
}
}
// This code is contributed by Smitha.
Python3
# Python3 code to find the
# maximum possible effort
# Function to get no of
# set bits in binary
# representation of positive
# integer n
def countSetBits(n) :
count = 0
while (n) :
count += n & 1
n >>= 1
return count
# Driver code
i = 3
print (countSetBits(i))
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
// C# code to find the maximum
// possible effort
using System;
class GFG {
// Function to get no. of
// set bits in binary
// representation of
// positive integer n
static int countSetBits(int n)
{
int count = 0;
while (n != 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
// Driver code
public static void Main(String[] args)
{
int i = 3;
Console.Write(countSetBits(i));
}
}
// This code is contributed by Smitha.
PHP
>= 1;
}
return $count;
}
// Driver code
$i = 3;
echo (countSetBits($i));
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
输出 :
2