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

📅  最后修改于: 2021-09-06 06:09:02             🧑  作者: Mango

给定一个由单个字母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)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live