A different way of thinking about the problem: Don’t use strings at all.
unsigned int filter(unsigned int x)
{
if(x < 5) // no more digits worth keeping. Time to head back and collect results.
{
return 0;
}
if (x%16 < 5) // exclude this digit
{
return filter(x >> 4); // return what we already have collected
}
else //include this number
{
return (filter(x >> 4) << 4) + x%16; // make room, collect digit.
}
}
filter
will call itself with one less digit (the least significant digit is removed) until there are no digits left worth collecting. Each call to filter looks at the least significant digit and decides to keep it by adding it to the end of the number that’s been accumulated on the way back or reject it.
More obvious (and should be just as fast once optimized)
unsigned int filter(unsigned int x)
{
if (x < 5) // no more digits worth keeping. Time to head back and collect results.
{
return 0;
}
unsigned int digit = x % 0x10; // isolate least significant hex digit
unsigned int remaining = x / 0x10; // remove least significant hex digit
unsigned int collected = filter(remaining); //process remaining input
if (digit >= 5) // collect this digit
{
collected = collected * 0x10 + digit; // make room and add digit.
}
return collected;
}
5
solved Decimal to hex conversion