集合Gk表示这样一堆数字,该集合内的数字有k个1

问题描述

集合Gk表示这样一堆数字,该集合内的数字有k个1。比如,G1 = { 1, 10, 100, 1000, ...} G2 = {11, 110, 1110 }, ... , Gk { ... }
给定一个数字,找出该数属于哪一个集合,并且返回该数在集合中的下标。

输入:6 = 110
输出:2  

代码实例

#include <stdio.h>
#include <limits.h>

long rankInGk(long n)
{
        long index = -1;
        long num1 = 0;
        
                long np = n;

        while(np) {
            num1++;
            np = np & (np - 1);
        }
    
                printf("%ld\n", num1);

        long i;
        for (i = 0; i < LONG_MAX; i++) {
            long numm1 = 0;

                   long icp = i;

            while (icp) {
                numm1++;
                icp = icp & (icp - 1);
            }

            if (numm1 == num1) {
                index++;

                if (i == n){
                    return index;
                }
            }

        }

        return index;

}

int main(int argc, char *argv[])
{
    long res;
    long _n;

        scanf("%ld", &_n);

    res = rankInGk(_n);
    printf("res:%ld\n", res);

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/dennis-wong/p/9180642.html