//c++模板元编程
#include <iostream>
using namespace std;
template<unsigned long N>
struct binary
{
static unsigned const value = binary<N / 10>::value * 2
+ N % 10;
};
template<>
struct binary<0>
{
static unsigned const value = 0;
};
int main()
{
cout << binary<1010>::value << endl;
return 0;
}
//递归算法
#include <iostream>
using namespace std;
unsigned binary(unsigned long N)
{
return 0 == N ? 0 : (N % 10 + 2 * binary(N / 10));
}
int main()
{
cout << binary(1010) << endl;
return 0;
}
//非递归算法
#include <iostream>
using namespace std;
unsigned binary(unsigned long N)
{
unsigned result = 0;
for(unsigned bit = 1; N; N /= 10, bit <<= 1) {
if(N % 10) {
result += bit;
}
}
return result;
}
int main()
{
cout << binary(1010) << endl;
return 0;
}