leetCode刷题记录之762 Prime Number of Set Bits in Binary Representation

题目原文

Given two integers L and R, find the count of numbers in the range [L, R] (inclusive) having a prime number of set bits in their binary representation.
(Recall that the number of set bits an integer has is the number of 1s present when written in binary. For example, 21 written in binary is 10101 which has 3 set bits. Also, 1 is not a prime.)

题目大意

给定2个整数表示一个区间,在这个区间里进行筛选,区间的数转换成2进制数,这个2进制数中包含1的个数如果是素数的话,这个数就满足要求,找出区间中满足上述要求的数的个数

/**
 * @param {number} L
 * @param {number} R
 * @return {number}
 */
var countPrimeSetBits = function(L, R) {
	var numOfSet = function(x)
    {	// 这个牛逼的方法是网上找的,找出2进制数中1的个数,参考剑指offer
		var countx = 0;
        while(x)
        {
            countx++;
            x = x&(x-1);
        }
        return countx;
    };
    var isPrime = function(x)
    {	// 判断是否素数
        if(x == 1) return false;
        for(var index = 2; index < x; index++)
        {
            if(x % index == 0) return false;       
        } 
        return true;
    };
    var retCount = 0;
    for(var index = L; index <= R; index++)
    {
        if(isPrime(numOfSet(index))) retCount++;
    }    
    return retCount;
};
发布了135 篇原创文章 · 获赞 10 · 访问量 6238

猜你喜欢

转载自blog.csdn.net/gunsmoke/article/details/104059650