求算术表达式中的某个变量值
写一个函数,参数是算术表达式字符串,返回值是表达式中的某个变量的值。
例如:
参数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;
}
大家来交流下 看怎么写?
public class ComputeExpress { private Dictionary<string, Func<int, int, int>> computeFunc = new Dictionary<string, Func<int, int, int>>(); public ComputeExpress() { computeFunc.Add("+", (x, y) => x + y); computeFunc.Add("-", (x, y) => x - y); computeFunc.Add("*", (x, y) => x * y); computeFunc.Add("+!", (x, y) => y - x); computeFunc.Add("-!", (x, y) => x + y); computeFunc.Add("!-", (x, y) => x - y); computeFunc.Add("*!", (x, y) => y / x); computeFunc.Add("!+", (x, y) => y - x); computeFunc.Add("!*", (x, y) => y / x); } public int GetResult(string express) { List<string> numbers = new List<string>(); string sign = ""; bool isLeft = true; StringBuilder builder = new StringBuilder(); foreach (var item in express) { if (item == '=') { isLeft = false; if (builder.Length > 0) { numbers.Add(builder.ToString()); } builder.Clear(); continue; } if (item == '?') { if (isLeft) { sign += "!"; } builder.Clear(); continue; } string tempStr = item.ToString(); if (isLeft && computeFunc.ContainsKey(tempStr)) { sign += tempStr; if (builder.Length > 0) { numbers.Add(builder.ToString()); } builder.Clear(); continue; } builder.Append(tempStr); } if (builder.Length > 0) { numbers.Add(builder.ToString()); } return computeFunc[sign](int.Parse(numbers[0]), int.Parse(numbers[1])); } }
可能还有点缺陷,表达式左边不能出现负数
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) }, { "-", new Func<int, int, int>((x, y) => x - y) }, { "*", new Func<int, int, int>((x, y) => x * y) }, { "/", new Func<int, int, int>((x, y) => x / y) } }; Dictionary<string, Func<int, int, int>> dict2 = new Dictionary<string, Func<int, int, int>>(); dict2.Add("+", dict1["-"]); dict2.Add("-", dict1["+"]); dict2.Add("*", dict1["/"]); dict2.Add("/", dict1["*"]); nums = nums.Where(x => x != "?").ToArray(); int result = (xpos == 0 || xpos == 1) ? dict2[op](int.Parse(nums[1]), int.Parse(nums[0])) : dict1[op](int.Parse(nums[0]), int.Parse(nums[1])); Console.WriteLine(result);我的想法就是写个parser, 用stack来运算。
不过这规模跟大学生上编译原理小作业一样大了。
不知有没有更好的方法……