Files
test/puzzles/interviews/training/negabinary.cpp
2021-11-22 11:12:39 +00:00

62 lines
1.4 KiB
C++

/*
VIM: let b:lcppflags="-std=c++2a -O2 -pthread -I."
VIM: let b:wcppflags="/O2 /EHsc /DWIN32"
VIM-: let b:argv=""
*/
#include <iostream>
#include <exception>
#include <chrono>
#include <type_traits>
#include <iomanip>
template <typename T>
constexpr T negabinary(T v){
static_assert(std::is_integral_v<T>, "Only integral types expected.");
const T base = -2;
const T abs_base = abs(base);
std::make_unsigned_t<T> n = 0;
int i = 0;
while ( v ){
T r = v % base;
v /= base;
if ( r < 0){
v +=1;
r = abs_base - r;
}
n |= std::make_unsigned_t<T>(r) << i;
++i;
}
return n;
}
int main ( void )
{try{
auto begin = std::chrono::high_resolution_clock::now();
for (int i = -16; i < 17; ++i){
std::cout << std::setbase(10) << i << " == " << std::setbase(16) << std::showbase << negabinary(i) << std::endl;
}
//std::cout << negabinary(2.) << std::endl;
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> seconds = end - begin;
std::cout << "Time: " << seconds.count() << std::endl;
return 0;
}
catch ( const std::exception& e )
{
std::cerr << std::endl
<< "std::exception(\"" << e.what() << "\")." << std::endl;
return 2;
}
catch ( ... )
{
std::cerr << std::endl
<< "unknown exception." << std::endl;
return 1;
}}