Power ofTotal accepted:11027 Total submissions:36750my submissions QuestionSolution
Given an integer, write a function to determine if it is a power of.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
Hide TagsMath Bit ManipulationHide Similar Problems(E) Number of 1 BitsHas you met this question in a real interview? Yes No
Discuss
The problem is to calculate whether a number is a 2 of the number of times, in fact, can be converted to calculate the number of bits on how many 1, it can be, the son this can be used bit operation method, that is, with a number n and n-1 bit and operation, you can remove a 1,
It is important to note that negative numbers must not be 2 of the time.
#include <iostream>using namespace Std;bool ispoweroftwo (int n) {if (n<0) return 0;int re=0;while (n) {re++;n=n & (n-1);} if (re==1) return 1;elsereturn 0;} int main () {cout<<ispoweroftwo (6) <<endl;}
leetcode_231 question--power of two (bitwise operations)