日期:2014-05-17  浏览次数:20889 次

求算术表达式中的某个变量值? (今天去某公司的面试题目)
求算术表达式中的某个变量值
写一个函数,参数是算术表达式字符串,返回值是表达式中的某个变量的值。
例如:
参数str="3*6=?",返回"?=18"。
参数str="6+?=10",返回"?=4"。
参数str="4-5=?",返回"?=-1"。
参数str="?-5=-4",返回"?=1"。
说明:三个变量(int类型)的运算(加、减、乘),已知两个变量,求第三个变量;


这个是今天上午去某公司面试的题目,想了好长时间,还是不会写这个函数。

        private string getresult(string str)
        {
            string result = "";
                 ......
           
            return result;
        }

------解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "5*10=?";
            string[] nums = s.Split('+', '-', '*', '/', '=');
            int xpos = nums.ToList().FindIndex(x => x == "?");
            string op = Regex.Match(s, @"[+\-*\/]").Value;
            Dictionary<string, Func<int, int, int>> dict1 = new Dictionary<string, Func<int, int, int>>()
            {
                { "+", new Func<int, int, int>((x, y) => x + y) },