Find whether a given number is a power of 4 or not
2013-06-09 14:12
507 查看
reference:
http://www.geeksforgeeks.org/find-whether-a-given-number-is-a-power-of-4-or-not/Problem Definition:
Find whether a given number is a power of 4 or not.
Solution:
A number n is a power of 4 if following conditions are met.a) There is only one bit set in the binary representation of n (or n is a power of 2)
b) The count of zero bits before the (only) set bit is even.
For example: 16 (10000) is power of 4 because there is only one bit set and count of 0s before the set bit is 4 which is even.
Code:
bool isPowerOfFour(unsigned int n) { int count = 0; /*Check if there is only one bit set in n*/ if ( n && !(n&(n-1)) ) { /* count 0 bits before set bit */ while(n > 1) { n >>= 1; count += 1; } /*If count is even then return true else false*/ return (count%2 == 0)? 1 :0; } /* If there are more than 1 bit set then n is not a power of 4*/ return 0; }
相关文章推荐
- Write one line C function to find whether a no is power of two
- leetCode Given an integer (signed 32 bits), write a function to check whether it is a power of 4
- Your task is to find for a given phone number any of its divisions into groups of two or three digit
- CareerCup Find whether a given number is a perfect square or not.(Addition and Subtraction only)
- Find whether an array is subset of another array
- P31 (**) Determine whether a given integer number is prime.
- P31 (**) Determine whether a given integer number is prime.
- Data Structure Array: Given an array of of size n and a number k, find all elements that appear more than n/k times
- Given life time of different animals. Find period when maximum number of animals lived
- You're given a string of lower-case Latin letters. Your task is to find the length of its longest su
- 【Leetcode】Given a binary tree, check whether it is a mirror of itself
- 76 What is the effect of increasing the value of the ASM_POWER_LIMIT parameter? A. The number of DBW
- Given an integer, write a function to determine if it is a power of two
- Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
- check a int number is power of 2?
- Given any integer 0 <= n <= 10000 not divisible by 2 or 5, some multiple of n is a number which in d
- Determine whether the concatenation of a and b in this order is a square number.
- FW - check whether tree is balanced or not - find the max and min of one tree- 2013年12月18日13:12:04
- isa - Determine whether input is object of given class matlab
- Find the number of subsets such that the sum of numbers in the subset is a prime number