本文主要是介绍二进制表示中质数个计算置位(LeetCode刷题 C语言),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。
(注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。)
示例 1:
输入: L = 6, R = 10
输出: 4
解释:
6 -> 110 (2 个计算置位,2 是质数)
7 -> 111 (3 个计算置位,3 是质数)
9 -> 1001 (2 个计算置位,2 是质数)
10-> 1010 (2 个计算置位,2 是质数)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation
结题思路:
使用联合,赋值给一个联合内部的一个值,然后使用位运算符判断某一位的具体指,然后相加,判断。
typedef union temp
{struct bit_s{unsigned int1:1;unsigned int2:1;unsigned int3:1;unsigned int4:1;unsigned int5:1;unsigned int6:1;unsigned int7:1;unsigned int8:1;unsigned int9:1;unsigned int10:1;unsigned int11:1;unsigned int12:1;unsigned int13:1;unsigned int14:1;unsigned int15:1;unsigned int16:1;unsigned int17 : 1;unsigned int18 : 1;unsigned int19 : 1;unsigned int20 : 1;unsigned int21 : 1;unsigned int22 : 1;unsigned int23 : 1;unsigned int24 : 1;unsigned int25 : 1;unsigned int26 : 1;unsigned int27 : 1;unsigned int28 : 1;unsigned int29 : 1;unsigned int30 : 1;unsigned int31 : 1;unsigned int32 : 1;}bit;unsigned int num;
} UNION;int countPrimeSetBits(int L, int R){UNION test;int i, returnValue, j;returnValue = 0;for(i = L; i <= R ; ++i){test.num = i;j = test.bit.int1 + test.bit.int2 + test.bit.int3 + test.bit.int4 + test.bit.int5 + test.bit.int6 + test.bit.int7 + test.bit.int8 + test.bit.int9 + test.bit.int10 + test.bit.int11 + test.bit.int12 + test.bit.int13 + test.bit.int14 + test.bit.int15 + test.bit.int16 + test.bit.int17 + test.bit.int18 + test.bit.int19 + test.bit.int20 + test.bit.int21 + test.bit.int22 + test.bit.int23 + test.bit.int24 + test.bit.int25 + test.bit.int26 + test.bit.int27 + test.bit.int28 + test.bit.int29 + test.bit.int30 + test.bit.int31 + test.bit.int32;if(j == 2 || j == 3|| j == 5 || j == 7 || j == 11 || j == 13 || j == 17 || j == 19 || j == 23 || j == 29){++returnValue;}}return returnValue;
}
这篇关于二进制表示中质数个计算置位(LeetCode刷题 C语言)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!