【剑指Offer学习】【面试题10 :二进制中1 的个数】

题目

【剑指Offer学习】【面试题10 :二进制中1 的个数】_第1张图片
image.png

解答

#import 

NSInteger numberOfOne(NSInteger n) {
    NSInteger count = 0;
    while (n != 0) {
        count++;
        n = (n - 1) & n;
    }
    return count;
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        NSLog(@"%ld", numberOfOne(9));
        NSLog(@"%ld", numberOfOne(3));
        NSLog(@"%ld", numberOfOne(4));
        NSLog(@"%ld", numberOfOne(5));
        NSLog(@"%ld", numberOfOne(8));
       
    }
    return 0;
}

你可能感兴趣的:(【剑指Offer学习】【面试题10 :二进制中1 的个数】)