📌  相关文章
📜  从给定表达式中找到缺失的数字x

📅  最后修改于: 2021-04-29 16:12:39             🧑  作者: Mango

给定一个字母数字字符串,由单个字母X组成,该字母X表示以下形式的表达式:

任务是评估整数A,B和C中任何一个中存在的缺失数字X ,以使给定表达式有效。

例子:

方法:请按照以下步骤解决问题:

  • 拆分字符串以提取两个操作数, 运算符和结果。
  • 检查结果中是否存在X。如果是这样,则通过对第一操作数和第二操作数与运算符施加的操作计算所得的值。
  • 否则,如果结果中不存在X。然后检查第一个操作数中是否存在X。如果是这样,则对第二个操作数应用运算,然后对运算运算符。
  • 否则,如果第一个操作数中也不存在X。然后检查第二个操作数中是否存在X。如果是这样,则对第一个操作数应用运算,然后对运算运算符。

下面是上述方法的实现:

Python3
# Python3 program to find missing
# digit x in expression
  
  
def MissingDigit(exp):
    
    # Split the expression to
    # extract operands, operator
    # and resultant
    exp = list(exp.split())
  
    first_operand = exp[0]
    operator = exp[1]
    second_operand = exp[2]
    resultant = exp[-1]
  
    # If x is present in resultant
    if 'x' in resultant:
        x = resultant
        first_operand = int(first_operand)
        second_operand = int(second_operand)
  
        if operator == '+':
            res = first_operand + second_operand
        elif operator == '-':
            res = first_operand - second_operand
        elif operator == '*':
            res = first_operand * second_operand
        else:
            res = first_operand // second_operand
  
     # If x in present in operands
    else:
  
        resultant = int(resultant)
  
        # If x in the first operand
        if 'x' in first_operand:
  
            x = first_operand
            second_operand = int(second_operand)
  
            if operator == '+':
                res = resultant - second_operand
            elif operator == '-':
                res = resultant + second_operand
            elif operator == '*':
                res = resultant // second_operand
            else:
                res = resultant * second_operand
  
        # If x is in the second operand
        else:
  
            x = second_operand
            first_operand = int(first_operand)
  
            if operator == '+':
                res = resultant-first_operand
            elif operator == '-':
                res = first_operand - resultant
            elif operator == '*':
                res = resultant // first_operand
            else:
                res = first_operand // resultant
  
    res = str(res)
    k = 0
    for i in x:
        if i == 'x':
            result = res[k]
            break
        else:
            k = k + 1
  
    return result
  
  
# Driver Code
if __name__ == '__main__':
    # input expression
    exp = "3x + 12 = 46"
  
    print(MissingDigit(exp))


输出:
4

时间复杂度: O(L),其中,方程式的长度。
辅助空间: O(1)