闲聊时提到了这个功能,有人觉得用后缀表达式好一些,也有建议用栈处理的。不可否认每种方法都有自己的特点和优势,但作为iOS开发人员,苹果为我们提供了很多方便的API接口,让我有了一个全新的处理思路。
在此整理分享,不足还望指出。
其实核心思路就是 充分的利用NSString 的 componentsSeparatedByString:方法 , 将运算符分隔开,并用递归的方法,逐个计算。
将加减先分割,再分割乘除 ,所以计算式中 将先运算乘除 , 再运算加减 , 进而达到算数优先级的效果。
附参考代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *number = @"2+5*3*2-4+7-9/3";
NSLog(@"计算器 : %@ = %ld",number,[self calculate:number]);
}
- (NSInteger)calculate:(NSString *)number{
NSInteger sum = 0;
if ([number containsString:@"+"] ||
[number containsString:@"-"] ||
[number containsString:@"*"] ||
[number containsString:@"/"]) {
if ([number containsString:@"+"]) {
NSArray *array = [number componentsSeparatedByString:@"+"];
for (NSString *num in array) {
sum += [self calculate:num.copy];
}
return sum;
}
if ([number containsString:@"-"]) {
NSArray *array = [number componentsSeparatedByString:@"-"];
sum = [self calculate:array.firstObject];
for (int i = 1; i < array.count ;i++) {
NSString *num = array[i];
sum -= [self calculate:num.copy];
}
return sum;
}
if ([number containsString:@"*"]) {
NSArray *array = [number componentsSeparatedByString:@"*"];
sum = 1;
for (NSString *num in array) {
sum *= [self calculate:num.copy];
}
return sum;
}
if ([number containsString:@"/"]) {
NSArray *array = [number componentsSeparatedByString:@"/"];
sum = [self calculate:array.firstObject];
for (int i = 1; i < array.count ;i++) {
NSString *num = array[i];
sum /= [self calculate:num.copy];
}
return sum;
}
}else{
sum = number.integerValue;
}
return sum;
}
网友评论