给定一个整数A ,任务是找到小于A的可能的最大值( B ),以使这两个数字A和B的异或等于它们的和,即A ^ B = A + B。
例子:
Input: A = 4
Output: 3
Explanation:
There are many such integers such that A ^ B = A + B
Some of this integers are –
4 ^ 3 = 4 + 3 = 7
4 ^ 2 = 4 + 2 = 6
4 ^ 1 = 4 + 1 = 5
4 ^ 0 = 4 + 0 = 4
Maximum of these values is 3
Input: 7
Output: 0
There is no integer except 0 such that A + B = A ^ B
方法:想法是利用以下事实:
并获得价值
,(A&B)的值必须等于0。
=> A & B = 0
=> B = ~A
例如:
A = 4 (1 0 0)
B = ~ A = (0 1 1) = 3
下面是上述方法的实现:
C++
// C++ implementation to find
// maximum value of B such that
// A ^ B = A + B
#include
using namespace std;
// Function to find the maximum
// value of B such that A^B = A+B
void maxValue(int a)
{
// Binary Representation of A
string c = bitset<3>(a).to_string();
string b = "";
// Loop to find the negation
// of the integer A
for(int i = 0; i < c.length(); i++)
{
if ((c[i] - '0') == 1)
b += '0';
else
b += '1';
}
// Output
cout << bitset<3>(b).to_ulong();
}
// Driver code
int main()
{
int a = 4;
// Function Call
maxValue(a);
return 0;
}
// This code is contributed by divyeshrabadiya07
Java
// Java implementation to find
// maximum value of B such that
// A ^ B = A + B
// Function to find the maximum
// value of B such that A^B = A+B
class GFG
{
static void maxValue(int a)
{
// Binary Representation of A
String c = Integer.toBinaryString(a);
String b = "";
// Loop to find the negation
// of the integer A
for (int i = 0; i < c.length(); i++)
{
if((c.charAt(i)-'0')==1)
b +='0';
else
b+='1';
}
// output
System.out.print(Integer.parseInt(b, 2));
}
// Driver Code
public static void main(String []args)
{
int a = 4;
// Function Call
maxValue(a);
}
}
// This code is contributed by chitranayal
Python3
# Python3 implementation to find
# maximum value of B such that
# A ^ B = A + B
# Function to find the maximum
# value of B such that A^B = A+B
def maxValue(a):
# Binary Representation of A
a = bin(a)[2:]
b = ''
# Loop to find the negation
# of the integer A
for i in list(a):
b += str(int(not int(i)))
# output
print(int(b, 2))
return int(b, 2)
# Driver Code
if __name__ == '__main__':
a = 4
# Function Call
maxValue(a)
C#
// C# implementation to find
// maximum value of B such that
// A ^ B = A + B
// Function to find the maximum
// value of B such that A^B = A+B
using System;
using System.Collections.Generic;
class GFG
{
static void maxValue(int a)
{
// Binary Representation of A
String c = Convert.ToString(a, 2);
String b = "";
// Loop to find the negation
// of the integer A
for (int i = 0; i < c.Length; i++)
{
if((c[i] - '0') == 1)
b += '0';
else
b += '1';
}
// output
Console.Write(Convert.ToInt32(b, 2));
}
// Driver Code
public static void Main(String []args)
{
int a = 4;
// Function Call
maxValue(a);
}
}
// This code is contributed by 29AjayKumar
输出:
3
性能分析:
- 时间复杂度:在上述方法中,存在从十进制到二进制的转换,在最坏的情况下需要O(logN)时间。因此,此方法的时间复杂度将为O(logN) 。
- 辅助空间复杂度:在上述方法中,没有使用额外的空间。因此,上述方法的辅助空间复杂度将为O(1)