jon Prime
jon Prime

Reputation: 51

Shifting digits in C

Is it possible to shift right the digits of an integer? I mean shifting the actual digits of the integer values and not the bits of its binary representation - for example shifting right the number 435 twice would result in 4. I want to know if there is a way to replace the rudimentary method of dividing the number by 10 the number of times that's equal to the number of digits you want to remove.

Thanks

Upvotes: 4

Views: 2713

Answers (2)

Marian
Marian

Reputation: 7472

If you are looking for speed, then I'd rely on compiler optimisation with the following code:

unsigned long long rshift(unsigned long long x, unsigned n) {
    switch(n){
    case 0: return(x);
    case 1: return(x/10);
    case 2: return(x/100);
    ...
    case 19: return(x/10000000000000000000ULL);
    default: if (x<10000000000000000000ULL) return(0);
             printf("Sorry, not yet implemented\n");
             return(0);
    }
}

Upvotes: 3

juhist
juhist

Reputation: 4314

If you think the rudimentary method is too slow, you can use the exponentiation by squaring algorithm to calculate a divisor: http://en.wikipedia.org/wiki/Exponentiation_by_squaring

Or you can use a lookup table:

int divisors_i[] = {1, 10, 100, 1000, 10*1000, ...}

unsigned long long divisors_ull[] = {1ULL, 10ULL, 100ULL, 1000ULL, 10ULL*1000ULL,
                                     100ULL*1000ULL, 1000ULL*1000ULL,
                                     10ULL*1000ULL*1000ULL, 100ULL*1000ULL*1000ULL, ...}

Be sure to select the appropriate data type for the lookup table. If you have an int, use the int lookup table. If you have an huge number, unsigned long long might be a better type to use.

The fastest way is the use of a lookup table. It is small enough to fit into the L1 cache of any CPU, so it is way faster than exponentiation by squaring.

Upvotes: 2

Related Questions