algorithm - What's the fastest way to obtain the highest decimal digit of an integer? -
this question has answer here:
what's fastest way implement
template <typename t> unsigned highest_decimal_digit(t x);
(which returns e.g. 3 356431, 7 71 , 9 9)?
the best can think of is:
- constexpr-calculate "middle-size" power of 10 fits t.
- perform binary search (over powers of 10, possibly using constexpr-constructed lookup table) find p, highest power-of-10 lower x.
- return x divided p
... maybe there's approach.
notes:
- i expressed question , approach in c++14ish terms, , solution in code nice, abstract solution (or solution in x86_64 assembly) fine. want work (unsigned) integer types, though.
- you may ignore signed integral types.
- i didn't specify "fast" is, hardware-conscious please.
the best option seems to combine clz approach , divide precalculated power of 10. so, in pseudocode:
powers10=[1,1,1,1,10,10,10,10,100,100...]; // contains powers of 10 map clz values int firstdigit(unsigned int_type a) { if (a<10) return a; // 1 digit, screw int j=typesize(a)-clz(a); if (j==3) return 1; // 10-16 hit this, return 1 int k=a/powers10[j]; if (k>9) return 1; else return k; }
typesize()
returns 64 long long
, 32 int
, 16 short int
.
Comments
Post a Comment