算法题:输入任意十进制正整数,将此十进制数转为二进制,求二进制中1的个数。

    
    int a = 10; // 10模拟任意整数
    NSMutableArray *array = [NSMutableArray array];
    while (a != 1) {
        int remainder = a % 2;
        [array addObject:@(remainder)]; // 存放二进制
        a = a / 2;
    }
    [array addObject:@(1)];
    int count = 0; // 1的个数
    for (NSNumber *value in array) {
        if ([value intValue] == 1) {
            count++;
        }
    }


    int count = 0; // 1的个数
    int a = 10; // 10模拟任意整数
    while (a > 0) {
        if (a % 2) {
            count++;
        }
        a = a / 2;
    }
a = 10

count = 0
while a != 0:
    if a % 2:
        count = count + 1
    a = a // 2

print(count)

// 位运算解法
a = 10
count = 0
while a:
    count += a & 1
    a >>= 1
print(count)

 

你可能感兴趣的:(数据结构与算法)