Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- // slowest
- int dCount1(unsigned int t1) {
- int t2=0;
- do {
- ++t2;
- } while ( ( t1 = t1 / 10 ) != 0 ) ;
- return t2;
- }
- // better since mul is faster than integer divide
- int dCount2 (unsigned int t1) {
- int t2 = 0, t3 = 1;
- while ( t3 <= t1 ) {
- ++t2;
- t3 *= 10;
- }
- return t2;
- }
- // best since array will be in L1 cache after first use so we just have an
- // increment and comparison.
- int dCount3(unsigned int t1) {
- unsigned int sizes[] = { 0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
- int t2 = 10;
- while ( t1 < sizes[t2] ) t2--;
- return t2;
- }
- int main(void) {
- unsigned int t1;
- char *str = "%d digits\n";
- while( scanf("%u", &t1) != EOF && t1 != 0 ) {
- printf(str, dCount1(t1));
- printf(str, dCount2(t1));
- printf(str, dCount3(t1));
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement