# 5年编程却被一道解决小学运算的面试题难倒 求算术表达式中的某个变量值

0
[已解决问题] 解决于 2013-09-15 16:16

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

return result;
}

0
```    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)
{
}
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)
{
}
builder.Clear();
continue;
}
builder.Append(tempStr);
}
if (builder.Length > 0)
{
}
return computeFunc[sign](int.Parse(numbers[0]), int.Parse(numbers[1]));

}

}```

sinhbv | 老鸟四级 |园豆：2579 | 2013-09-15 14:51
` ``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);`

0

akisann | 园豆：341 (菜鸟二级) | 2013-09-15 14:27

您需要登录以后才能回答，未注册用户请先注册