You can try something like this:
template<typename T> T nozeros( T const & z ) { return z==0 ? 0 : (z%10?10:1)*nozeros(z/10)+(z%10); }
If you want to do your processing one more step, you can do a good tail recursion, no need to use a helper function:
template<typename T> inline T pow10(T p, T res=1) { return p==0 ? res : pow10(--p,res*10); } template<typename T> T nozeros( T const & z , T const & r=0, T const & zp =0) { static int digit =-1; return not ( z ^ r ) ? digit=-1, zp : nozeros(z/10,z%10, r ? r*pow10(++digit)+zp : zp); }
Here's how it will work with input 32040
Ret, z, r, zp, numbers
-, 32040,0,0, -1
-, 3204,0,0, -1
-, 320,4,0,0, -1
-, 32,0,4,4, 0
-, 3,2,4, 0
-, 0.3.24, 1
-, 0,0,324, 2
324, -, -, -, -1
Integer calculations are always faster than actually converting integers to a string, comparing strings and finding strings to return them to integers.
The most interesting thing is that if you try to pass floats, you get good compile-time errors.
I argue that this is slightly faster than other solutions, as it makes less conditional estimates that will allow you to behave better with CPU branch prediction.
source share