Created
January 4, 2016 00:39
-
-
Save hamsham/e0d0f38f823b7d51da00 to your computer and use it in GitHub Desktop.
Count the number of leading and trailing zeroes in an integer.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Count the number of leading and trailing zeroes in an integer | |
* | |
* g++ -std=c++11 -Wall -Wextra -Werror -pedantic-errors num_zeros.cpp -o num_zeros | |
*/ | |
#include <iostream> | |
#include <cstdint> | |
template <typename int_t> | |
constexpr int_t num_trailing_zeros(int_t i, unsigned numZeros = 0) { | |
return !i ? numZeros : num_trailing_zeros(i >> 1, numZeros+1); | |
} | |
template <typename int_t> | |
constexpr int_t num_leading_zeros(int_t i) { | |
return (sizeof(int_t) * CHAR_BIT) - num_trailing_zeros(i); | |
} | |
int main() { | |
std::cout << num_leading_zeros(1) << std::endl; | |
std::cout << num_leading_zeros(2) << std::endl; | |
std::cout << num_leading_zeros(3) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment