给定两个正数和不同的数,任务是在不使用任何条件语句(if…)和运算符(?:在C / C++ / Java)的情况下,找到两个给定数中的最大值。
例子:
Input: a = 14, b = 15
Output: 15
Input: a = 1233133, b = 124
Output: 1233133
方法是根据以下表达式返回值:
a * (bool)(a / b) + b * (bool)(b / a)
如果a> b,则表达式a / b将给出1,如果a 因此,答案将采用a + 0或0 + b的形式,具体取决于哪个更大。
C++
// C++ program for above implementation
#include
using namespace std;
// Function to find the largest number
int largestNum(int a, int b)
{
return a * (bool)(a / b) + b * (bool)(b / a);
}
// Drivers code
int main()
{
int a = 22, b = 1231;
cout << largestNum(a, b);
return 0;
}
Java
// Java program for above implementation
class GFG
{
// Function to find the largest number
static int largestNum(int a, int b)
{
return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0);
}
// Drivers code
public static void main(String[] args)
{
int a = 22, b = 1231;
System.out.print(largestNum(a, b));
}
}
// This code is contributed by 29AjayKumar
Python3
# Function to find the largest number
def largestNum(a, b):
return a * (bool)(a // b) + \
b * (bool)(b // a);
# Driver Code
a = 22;
b = 1231;
print(largestNum(a, b));
# This code is contributed by Rajput-Ji
C#
// C# program for above implementation
using System;
class GFG
{
// Function to find the largest number
static int largestNum(int a, int b)
{
return a * ((a / b) > 0 ? 1 : 0) + b * ((b / a) > 0 ? 1 : 0);
}
// Driver code
public static void Main(String[] args)
{
int a = 22, b = 1231;
Console.Write(largestNum(a, b));
}
}
// This code is contributed by Rajput-Ji
PHP
Javascript
输出:
1231