Object-C 栈的应用实现两个大数相加

2020-05-11  本文已影响0人  劉胡來
NSLog(@"72----------byte:%ld  max :%ld min:%ld",sizeof(NSInteger),NSIntegerMax,NSIntegerMin);
  • 读入第一个数的数字num1,并将这些数字存到一个栈中(假设为Stack1);
  • 读入第二个数的数字num2,并将这些数字存到一个栈中(假设为Stack2);
  • 定义一个用来保存进位的变量plus = 0;
  • while(至少一个栈不空):
    1.从每一个非空的栈弹出一个数,将这两个数字与plus相加;
    2.将个位数存入结果栈中(resultStack);
    3.判断是否发生进位(判断num1 + num2 > 9),如果发生进位,将进位存入plus中,否则将plus 恢复为0;
  • 如果进位不为0,将其存入结果栈中;
  • 从结果栈弹出结果返回即可;
image.png
#import "AddLargeNumber.h"
#import "Stack.h"

@interface AddLargeNumber()
@property(nonatomic,strong) Stack* operatorStack1;
@property(nonatomic,strong) Stack* operatorStack2;
@property(nonatomic,strong) Stack* resultStack;

@end

@implementation AddLargeNumber


-(NSString*) addLargeNumber:(NSString*) number1 number2:(NSString*) number2{
    NSMutableString* result = [[NSMutableString alloc] init];
    if (!self.operatorStack1) {
        self.operatorStack1 = [[Stack alloc] initWithSize:[number1 length]];
    }
    if (!self.operatorStack2) {
        self.operatorStack2 = [[Stack alloc] initWithSize:[number2 length]];
    }
    
    if (!self.resultStack) {
        self.resultStack = [[Stack alloc] initWithSize:[number1 length] + [number2 length]];
    }
    
    for(int i = 0;i < [number1 length]; i++){
        NSString *ch = [number1 substringWithRange:NSMakeRange(i,1)];
        [self.operatorStack1 push:ch];
    }
    
    for(int i = 0;i < [number2 length]; i++){
        NSString *ch = [number2 substringWithRange:NSMakeRange(i,1)];
        [self.operatorStack2 push:ch];
    }
    [self.operatorStack1 test];
    [self.operatorStack2 test];
    NSInteger carry = 0;
    while(![self.operatorStack1 isEmpty] || ![self.operatorStack2 isEmpty]){
        NSInteger opt1 = 0;
        NSInteger opt2 = 0;
        if(![self.operatorStack1 isEmpty]){
            opt1 = [(NSString*)[self.operatorStack1 pop] intValue] ;
        }
        if(![self.operatorStack2 isEmpty]){
            opt2 = [(NSString*)[self.operatorStack2 pop] intValue] ;
        }
        NSInteger tmpResult = opt1 + opt2 + carry;
        if (tmpResult > 9) {  //发生进位
            carry = 1;
            NSInteger geWei = tmpResult - 10;
            [self.resultStack push:[NSString stringWithFormat:@"%ld",geWei]];
        }else{
            carry = 0;
            [self.resultStack push:[NSString stringWithFormat:@"%ld",tmpResult]];
        }
        [self.resultStack test];
    }

    while (![self.resultStack isEmpty]) {
        NSString* tmp = (NSString*)[self.resultStack pop];
        [result appendString:tmp];
    }
    return [result copy];
    
}

@end

书籍参考 《数据结构C++版》

上一篇下一篇

猜你喜欢

热点阅读