📌  相关文章
📜  给定范围内的最大按位与对(X,Y),使得X和Y可以相同

📅  最后修改于: 2021-05-25 09:42:37             🧑  作者: Mango

在给定范围[L,R]的情况下,任务是找到一个不一定是对的(X,Y)。找到所选整数的按位与的最大可能值。
例子:

幼稚的方法:为了解决上述问题,幼稚的方法是从L迭代到R,并检查每个可能的对的按位与,并在最后打印最大值。
时间复杂度: O(N 2 )
高效方法:
为了优化上述方法,我们必须观察到,这里我们必须对L和R进行整数处理,并且必须从区间[L,R]中选择两个整数,以使它们的按位与最大。 L和R之间任意两个数字的按位与将始终始终小于或等于R。因此,如果必须从间隔中选择两个整数,则可以将整数选择为R,这是最大化按位与的唯一方法。
下面是上述方法的实现:

C
// C implementation to find the
// Maximum Bitwise AND pair (X, Y)
// from given range such that
// X and Y can be same
 
#include 
 
// Function to return the
// maximum bitwise AND
int maximumAND(int L, int R)
{
    return R;
}
 
// Driver code
int main()
{
    int l = 3;
    int r = 7;
 
    printf("%d", maximumAND(l, r));
 
    return 0;
}


C++
// C++ implementation to find the
// Maximum Bitwise AND pair (X, Y)
// from given range such that
// X and Y can be same
 
#include 
using namespace std;
 
// Function to return the
// maximum bitwise AND
int maximumAND(int L, int R)
{
    return R;
}
 
// Driver code
int main()
{
    int l = 3;
    int r = 7;
 
    cout << maximumAND(l, r);
 
    return 0;
}


Java
// Java implementation to find the
// Maximum Bitwise AND pair (X, Y)
// from given range such that
// X and Y can be same
 
class GFG {
 
    // Function to return the
    // maximum bitwise AND
    static int maximumAND(int L, int R)
    {
        return R;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int l = 3;
        int r = 7;
        System.out.print(maximumAND(l, r));
    }
}


Python3
# Python3 implementation to find the
# Maximum Bitwise AND pair (X, Y)
# from given range such that
# X and Y can be same
 
# Function to return the
# maximum bitwise AND
def maximumAND(L, R):
    return R
 
# Driver code
if __name__ == '__main__':
    l = 3
    r = 7
    print(maximumAND(l, r))


C#
// C# implementation to find the
// maximum Bitwise AND pair (X, Y)
// from given range such that
// X and Y can be same
using System;
 
class GFG{
 
// Function to return the
// maximum bitwise AND
static int maximumAND(int L, int R)
{
    return R;
}
 
// Driver code
public static void Main(String[] args)
{
    int l = 3;
    int r = 7;
     
    Console.Write(maximumAND(l, r));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
7

时间复杂度: O(1)