当前浏览器不支持播放音乐或语音,请在微信或其他浏览器中播放
Everything at Once Lenka - Two (Bonus Track Version)
前言
Day04介绍了Reverse Polish Notation,主要是为了方便用栈这个结构计算数学表达式。复习下:
输入前:(3 + 2)*(4 + 6) 转化后:3 2 + 4 6 + * 结果:50
流程图

主要代码
- (int)evaluateRPN:(NSString *)inputStr
{
DSStack *newStack = [[DSStack alloc] initWithSize:10];
for (int i =0 ; i<inputStr.length; i++)
{
unichar tempChar = [inputStr characterAtIndex:i];
if ([[NSString stringWithCharacters:&tempChar length:1] isEqualToString:@"*"])
{
NSNumber *a = [newStack popLastObject];
NSNumber *b = [newStack popLastObject];
[newStack push:[NSNumber numberWithInt:([a intValue]*[b intValue])]];
}
else if ([[NSString stringWithCharacters:&tempChar length:1] isEqualToString:@"/"])
{
NSNumber *a = [newStack popLastObject];
NSNumber *b = [newStack popLastObject];
[newStack push:[NSNumber numberWithInt:([a intValue]/[b intValue])]];
}
else if ([[NSString stringWithCharacters:&tempChar length:1] isEqualToString:@"+"])
{
NSNumber *a = [newStack popLastObject];
NSNumber *b = [newStack popLastObject];
[newStack push:[NSNumber numberWithInt:([a intValue]+[b intValue])]];
}
else if ([[NSString stringWithCharacters:&tempChar length:1] isEqualToString:@"-"])
{
NSNumber *a = [newStack popLastObject];
NSNumber *b = [newStack popLastObject];
[newStack push:[NSNumber numberWithInt:([a intValue]-[b intValue])]];
}
else
{
[newStack push:[NSNumber numberWithInt:[[NSString stringWithCharacters:&tempChar length:1] intValue]]];
}
}
return [[newStack popLastObject] intValue];
}
大致思路描述
-
把中缀表达式转化为Reverse Polish Notation。
-
按照顺序进栈。
-
当进栈的元素是 ( + - * / )四个运算符,则弹出栈顶两个元素并计算,并且把结果入栈。
-
最终栈只剩下一个元素,这个元素就是最后的值。
GitHubDemo
GitHub链接 [1]
关注公众号最新动态

References
[1] GithubDemo: https://github.com/renmoqiqi/100-Days-Of-iOS-DataStructure-Algorithm/tree/master/Day05