题解 | #查找输入整数二进制中1的个数(多行)#

查找输入整数二进制中1的个数

https://www.nowcoder.com/practice/1b46eb4cf3fa49b9965ac3c2c1caf5ad

#import <Foundation/Foundation.h>

int main(int argc, char* argv[]) {
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    char inputNum[10000];
    NSInteger lineNum = 0;
    NSMutableArray* array = [NSMutableArray array];
    while (fgets(inputNum, sizeof(inputNum), stdin) != NULL && lineNum <= 1000) {
        inputNum[strcspn(inputNum, "\n")] = '\0';
        [array addObject:[NSString stringWithFormat:@"%s", inputNum]];
        lineNum ++;
    }

    NSMutableArray* resultArray = [NSMutableArray array];
    for (int i = 0; i < array.count; i++) {
        NSInteger count = 0;
        int number = [[array objectAtIndex:i] intValue];
        while (number) {
            if (number & 1) {
                count ++;
            }
            number >>= 1;
        }
        [resultArray addObject:[NSString stringWithFormat:@"%d", count]];
    }
    for (int i = 0; i < resultArray.count; i++) {
        printf("%@\n", [resultArray objectAtIndex:i]);
    }

    [pool drain];
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务