📜  最多四个数字,而不使用条件运算符或按位运算运算符

📅  最后修改于: 2021-05-20 05:23:22             🧑  作者: Mango

给定四个数字,不使用条件运算符或按位运算运算符(甚至不包括三元运算符),即可打印输入的4个数字中的最大值。

例子:

Input : 4 8 6 5
Output : 8

Input : 11 17 8 17
Output : 17

我们使用这样的事实:“(x – y + abs(x – y))”的值将为x的0小于或等于y。我们将此值用作大小为2的数组中的索引以选择最大值。一旦找到两个元素的最大值,就可以使用相同的技术来找到所有元素的最大值。

C++
// CPP program to find maximum of 4 numbers
// without using conditional and bitwise
// operators.
#include 
using namespace std;
  
int maxOfFour(int w, int x, int y, int z)
{
    int a[2];
    a[0] = w, a[1] = x;
  
    // b is 0 if w is less than or equal
    // to x, else it is non-zero.
    bool b = (a[0] - a[1] + abs(a[0] - a[1]));
  
    // After below operation, a[0] is maximum
    // of w and x.
    swap(a[0], a[!b]);
  
    // After below three steps, a[0] is maximum
    // of w, x and y.
    a[1] = y;
    b = (a[0] - a[1] + abs(a[0] - a[1]));
    swap(a[0], a[!b]);
  
    // After below three steps, a[0] is maximum
    // of w, x, y and z.
    a[1] = z;
    b = (a[0] - a[1] + abs(a[0] - a[1]));
    swap(a[0], a[!b]);
  
    return a[0];
}
  
// Driver code
int main()
{
    int w = 12, x = 15, y = 18, z = 17;
    cout << "Maximum of four : "
         << maxOfFour(w, x, y, z);
    return 0;
}


Python
# Python program to find maximum of 4 numbers 
# without using conditional and bitwise 
# operators. 
def maxOfFour(w, x, y, z):
    a = [0] * 2
    a[0] = w
    a[1] = x 
      
    # b is 0 if w is less than or equal 
    # to x, else it is non-zero. 
    b = bool(a[0] - a[1] + abs(a[0] - a[1]))
    if b: 
        b = 1
    else: 
        b = 0
  
    # After below operation, a[0] is maximum 
    # of w and x. 
    a[0], a[1 - b] = a[1 - b], a[0]
      
    # After below three steps, a[0] is maximum 
    # of w, x and y. 
    a[1] = y 
    b = bool(a[0] - a[1] + abs(a[0] - a[1])) 
    if b: 
        b = 1
    else: 
        b = 0
    a[0], a[1 - b] = a[1 - b], a[0]
      
    # After below three steps, a[0] is maximum 
    # of w, x, y and z. 
    a[1] = z 
    b = bool(a[0] - a[1] + abs(a[0] - a[1]))
    if b: 
        b = 1
    else: 
        b = 0
    a[0], a[1 - b] = a[1 - b], a[0]
      
    return a[0] 
  
# Driver code 
w = 12
x = 15
y = 18
z = 17
print("Maximum of four : ", maxOfFour(w, x, y, z))
  
# This code is contributed by SHUBHAMSINGH10


输出:

Maximum of four : 18