__builtin_popcount(n)

Gcc提供的内建函数__builtin_popcount(n),可以精确计算n表示成二进制时有多少个1。借助这个函数可以快速判断一个数是否是2的幂。

1 bool isPowerOfTwo(int n)
2 {
3     return n>0 && __builtin_popcount(n)==1;
4 }
时间: 2024-08-12 14:03:09

__builtin_popcount(n)的相关文章

__builtin_popcount() 函数

详解 该函数的主要作用是计算一个数字的二进制中有多少个1,返回值就是其中1的个数. 它使用一张基于表的方法来进行位搜索,因此这个操作的执行效率很高 此处举一题 P1582 倒水 #include <bits/stdc++.h> using namespace std; #define lowbit(x) x&(-x) int main() { int n,k; scanf("%d%d",&n,&k); int ans=n; while(__built

hdu 5898 odd-even number 数位DP

odd-even number Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 716    Accepted Submission(s): 385 Problem Description For a number,if the length of continuous odd digits is even and the length

hdu 5719 BestCoder 2nd Anniversary B Arrange 简单计数问题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5719 题意:一个数列为1~N的排列,给定mn[1...n]和mx[1...n],问有符合的排列数为多少?如果不存在,输出0: 思路: 有解的几种条件: 1. mn , mx 变化单调: 2. mn,mx 不能同时变化: 3. 一个位置可选的个数>0; 当解存在时,递推出每次可选择的个数,num += mx[i] - mx[i-1] + mn[i-1] - mn[i] - 1; 即可: 坑:开始想成了

glibc中几个有用的处理二进制们的内置函数

说明:因为在牡丹江网络赛中看见北大AC非常简洁的代码里面把二进制用得是炉火纯青,在里面看见了处理二进制的函数,所以咱也学一下. (1) - Built-in Function: int __builtin_ffs (unsigned int x) Returns one plus the index of the least significant 1-bit of x, or if x is zero, returns zero. 返回右起第一个'1'的位置. (2) - Built-in F

2017盛大游戏杯 零件组装(状态压缩DP之巧妙枚举子集)

题目链接:2017盛大游戏杯 零件组装 题意: 有n个零件,给你相邻关系和排斥关系,每两块零件组装起来有一个代价,问最少的代价总和是多少. 题解: 考虑状态压缩,dp[i]表示i这个集合为一个零件块. 那么要枚举一下i的子集.O(3^n). 先要预处理一下每个集合的排斥个数和相邻个数,然后容斥一下就可以了. 1 #include<bits/stdc++.h> 2 #define mst(a,b) memset(a,b,sizeof(a)) 3 #define F(i,a,b) for(int

[LeetCode]Reverse Bits

题目:Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have already thought through thi

338. 1的位数 Counting Bits

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example:For num = 5 you should return [0,1,1,2,1,2]. Follow up: It is very e

POJ2104 K-th Number [分块做法]

传送:主席树做法http://www.cnblogs.com/candy99/p/6160704.html 做那倒带修改的主席树时就发现分块可以做,然后就试了试 思想和教主的魔法差不多,只不过那个是求>=v的有几个 既然一个数v的名次可以求,我们二分这个数就行了啊 然而...... 首先,你二分到的这个数不一定在区间里出现过 比如 1 2 5 8 9 4和5的名次都是3 于是,我修改了某个区间名次的定义: “如果一个数的名次是x,但是区间中没有次数,那么他的名次为x-1” 实现上只需要find里

[HDOJ5876]Sparse Graph(补图最短路)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5876 题意:求一个图的补图中的单源最短路. 题解说:补图上的 BFS 是非常经典的问题.一般的做法是用链表(或者偷懒用 std::set)维护还没 BFS 过的点.当要扩展点 u 的时候,遍历一次还没访问过的点 v,如果 uv 没边,那么将 v 入队.否则将 v 留在未扩展点中.很明显,后者只会发生 m 次,前者只会发生 n 次,所以复杂度是 O(n + m). 总得说,求补图的最短路就是要存原图,