一个简单的算法 - 将一个正整数拆分成指定几个正整数的组合

假设我们这里有个正整数18,这里需要把18拆分成1 2 3 5 10的组合,那么输出的结果应该是:
==> 10+5+3
eg:->79 ----->7*10+5+3+1 大数优先
类似这样的效果,这里写了一个简单的算法来实现
SModel.h

#import 

@interface SModel : NSObject

@property (nonatomic,assign) NSInteger totalCount;  //总个数

@property (nonatomic,assign) NSInteger count10;   //10的个数

@property (nonatomic,assign) NSInteger count5;  //5的个数

@property (nonatomic,assign) NSInteger count3;  //3的个数

@property (nonatomic,assign) NSInteger count2;  //2的个数

@property (nonatomic,assign) NSInteger count1;  //1的个数

@property (nonatomic,strong) NSMutableArray *sArr;

@end

拆分方法

-(SModel*)splitScore:(NSInteger)score{
    NSInteger y = 0;  //余数
    SModel *model = [[SModel alloc] init];
    do {
        if (score >= 10) {
            y = score%10;
            score = score/10;
            NSLog(@"%zix10",score);
            model.totalCount+=score;
            model.count10 = score;
            score = y;
            
        }else if(score >= 5){
            y = score%5;
            score = score/5;
            NSLog(@"%zix5",score);
            model.totalCount+=score;
            model.count5 = score;
            score = y;
            
        }else if(score >= 3){
            y = score%3;
            score = score/3;
            NSLog(@"%zix3",score);
            model.totalCount+=score;
            model.count3 = score;
            score = y;
        }else {
            NSLog(@"%zi",score);
            model.count1 = score;
            model.totalCount+=score;
            score = y;
            break;
        }
    }while (1);
    
    return model;
}

计算完成之后通过一个Model把数据存储起来,包括总的拆分的个数,1 2 3 5 10每个数字的个数,最后拿到模型就可以去处理相应的逻辑
类似这样的功能和纸牌游戏中的加注功能类似

转载于:https://www.cnblogs.com/qqcc1388/p/6768079.html

你可能感兴趣的:(一个简单的算法 - 将一个正整数拆分成指定几个正整数的组合)