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

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

作者: 林大鹏 | 来源:发表于2018-01-30 16:59 被阅读11次

题目

image.png

解答

#import <Foundation/Foundation.h>

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 的个数】

      本文链接:https://www.haomeiwen.com/subject/hksiaxtx.html