我在面试时得到了这个问题,但却无法获得两位数字。
public class MyServiceTests : TestServerDependent
{
public MyServiceTests(TestServerFixture fixture)
: base(fixture)
{
}
[Fact]
public void ReturnsDataWhenServiceInjected()
{
var service = GetService<IMyService>();
Assert.NotNull(service);
var data = service.GetData();
Assert.NotNull(data);
}
}
例如:
输入:20 + 30-45 * 60
输出:60 * 45-30 + 20
答案 0 :(得分:2)
很简单,现在当你真的需要推动令牌时,你会推动角色。
假设没有担心的括号,请保留一个字符串以添加数字,并且只有在您到达非数字时才推送它。当你继续抓取数字时,将字符附加到该字符串的末尾(如果你想提高效率,可能就是StringBuilder ......)
答案 1 :(得分:0)
如果您需要使用Stack
,则应该可以使用:
private static void reverse(String s) {
String[] operators = {"\\+", "-", "\\*", "/"};
for (String op : operators) {
s = s.replaceAll(op, " " + op + " ");
}
String[] splitted = s.split(" ");
Stack st=new Stack<>();
for (int i = 0; i < splitted.length; i++) {
st.push(splitted[i]);
}
System.out.println("popping values");
while(!st.isEmpty()) {
System.out.print(st.pop());
}
}
public static void main(String[] args) {
String s="20+30-45*60";
reverse(s);
}
将打印:
60*45-30+20
没有的Stack
更加简单:
private static void reverse(String s) {
String[] operators = {"\\+", "-", "\\*", "/"};
for (String op : operators) {
s = s.replaceAll(op, " " + op + " ");
}
String[] splitted = s.split(" ");
for (int i = splitted.length - 1; i >= 0; i--) {
System.out.print(splitted[i]);
}
}