码迷,mamicode.com
首页 > 编程语言 > 详细

几个算法

时间:2015-11-23 12:57:38      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

1.数字转汉字(十万以内)

  a.算法

+ (NSString *)chinaNumberWithIndex:(NSUInteger)index{
    if (index == 0) { //特殊处理
        return @"";
    }
    NSString *str = [NSString stringWithFormat:@"%ld",index];
    NSString *result = @"";
    NSInteger lastmm = 0;
    NSArray *array = @[@"",@"",@"",@"",@"",@"",@"",@"",@"",@""];
    NSArray *arr   = @[@"",@"",@"",@"",@""];
    for (int i = 0; i < str.length; i ++) {
        NSInteger mm = index % 10;
        index /= 10;
        if (i == 0) {
            if (mm != 0) {
                result = [array objectAtIndex:mm];
            }
            lastmm = mm;
        }else{
            if (str.length == 2 && i == 1 && mm == 1) { //11  读作 十一而非一十一 ,特殊处理
                result = [NSString stringWithFormat:@"十%@",result];
            }else
            if (mm == 0) {
                if (mm != lastmm) {
                    result = [NSString stringWithFormat:@"零%@",result];
                }
            }else{
                result = [NSString stringWithFormat:@"%@%@%@",[array objectAtIndex:mm],[arr objectAtIndex:i],result];
            }
            lastmm = mm;
        }
    }
    return result;
}

  b.调用

    int index = arc4random_uniform(100000);
    NSLog(@"%d:%@",index,[ViewController chinaNumberWithIndex:index]);

   c.打印

14833:一万四千八百三十三

 2.获取某个数字以内的几个随机数

   a.算法

-(NSIndexSet *)getRandomWithIndex:(NSInteger)number count:(NSInteger)count{
    if (number > count) {
        return nil;
    }
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 0; i < count; i ++) {
        [array addObject:[NSString stringWithFormat:@"%d",i]];
    }
    NSMutableIndexSet *indexSet2 = [NSMutableIndexSet indexSet];
    for (int i = 0 ; i < number; i ++) {
        int index = arc4random_uniform((int)array.count);
        NSString *str = [array objectAtIndex:index];
        [indexSet2 addIndex:[str integerValue]];
        [array removeObject:str];
    }
    return [[NSIndexSet alloc]initWithIndexSet:indexSet2];
}

 b.调用

 NSLog(@"%@",[self getRandomWithIndex:9 count:89]);

 c.打印

<NSIndexSet: 0x7fdc48cbb5f0>[number of indexes: 9 (in 8 ranges), indexes: (9 16 30 38 69 76-77 84 88)]

 

几个算法

标签:

原文地址:http://www.cnblogs.com/gulong/p/4987822.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!