1 点赞
3 评论
【守望者 java经典笔试题】一道华为JAVA比武大赛试题,你能解答吗?
1536 次浏览
2014-09-07 12:01
显示评论
问题描述: 据说这是华为2005年中央平台开发部的JAVA比武大赛中的必做题,当时难倒了不少人。你能够给出最佳答案吗?把你的代码帖出来,看看谁的算法最简单最高效。要求://///////////////////input.txt样例////////////////// ... 查看更多>>
-
-
c#版本源码:
using System.Collections.Generic;
using System.Text;namespace ConsoleStudy
{
class Program
{
static void Main(string[] args)
{
string input = string.Empty;
while (true)
{
input = Console.ReadLine(); //"1+2+3*4"; if (input == "q")
{
break;
}
else
{
int res = Arithmetic.CalcIt(input);
Console.WriteLine(res);
}
}
} }
}
----------- using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleStudy
{
class CommandChar
{
char cmdType = ' '; public char CmdType
{
get { return cmdType; }
//set { cmdType = value; }
}
public CommandChar(char s)
{
cmdType = s;
} public int Pri
{
get
{
switch (cmdType)
{
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '%':
return 2;
default:
return 0;
}
}
} public static int BjPri(CommandChar c1, CommandChar c2)
{
return c1.Pri - c2.Pri;
}
}
}
--------- using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleStudy
{
public class Arithmetic
{
public static int CalcIt(string input)
{
List<string> inputs = split(input);
while (inputs.Count > 1)
{
inputs = CalcBody(inputs);
}
return int.Parse(inputs[0]);
} private static List<string> CalcBody(List<string> inputs)
{
Stack<string> stack = new Stack<string>(); CommandChar preCom = new CommandChar(' ');
foreach (string c in inputs)
{
if (isOper(c))
{
CommandChar cc = new CommandChar(c[0]); if (CommandChar.BjPri(preCom, cc) >= 0)
{
string n2 = stack.Pop();
string o = stack.Pop();
string n1 = stack.Pop();
string r = Arithmetic.calc(n1, o, n2); stack.Push(r);
} stack.Push(c);
preCom = cc;
}
else
{
stack.Push(c);
}
}
inputs.Clear(); if (stack.Count > 3)
{
while (stack.Count > 0)
{
inputs.Add(stack.Pop());
}
}
else
{
string n2 = stack.Pop();
string o = stack.Pop();
string n1 = stack.Pop();
string r = Arithmetic.calc(n1, o, n2); inputs.Add(r);
} return inputs;
} public static List<string> split(string input)
{ List<string> ls = new List<string>();
string s = string.Empty;
foreach (char c in input)
{
if (isOper(c))
{
if (s != string.Empty)
{
ls.Add(s);
s = string.Empty;
}
string o = string.Empty;
o += c;
ls.Add(o);
}
else
{
s += c;
} } ls.Add(s);
return ls;
} private static string calc(string n1, string Op, string n2)
{
int i1 = int.Parse(n1);
int i2 = int.Parse(n2);
int r = 0;
switch (Op)
{
case "+":
{
r = i1 + i2;
break;
}
case "-":
{
r = i1 - i2;
break;
} case "*":
{
r = i1 * i2;
break;
}
case "/":
{
r = i1 / i2;
break;
} } return r.ToString();
} private static bool isOper(char c)
{
if (c == '+' || c == '-' || c == '*' || c == '/')
{
return true;
}
else
{
return false;
}
} private static bool isOper(string c)
{
return isOper(c[0]);
} }
}
-
-
-