posted 6 years ago
hi Ranajoy,
I must admit: it is a very nice way to discover a pandigital.
What happens here is that this method puts a '1' on bit location n-1, given a current digital of n.
If it then is working on a digital t, it checks if bit number t-1 is a '1' or not. If it is a '1', that
means it has seen this digit before, so the number in question cannot be a pandigital.
I guess this sounds pretty unclear. So let's try an example. Say, the number in question is 424.
Now, in the first pass, digits = 0, and so is tmp. Then follows the trick.
First, the last digit is determined, i.e. 4, by the standard method: digit = n % 10.
Then, it takes 1, shifts it (4 - 1) = 3 places to the left, and 'OR''s it with digits.
digits now becomes the binary '1000'.
So, in effect, it puts a '1' in the fourth place from the right, using the bits in 'digits'
as an array.
Then it does: n = n / 10. So n = 42.
The last digit now is 2. So it shifts a '1' one (2 - 1) place to the left, we then get the number '10'
(in binary), and 'OR's it with digits, giving the number '1010'. As you can see, using the bits of
'digits' as a sort of array, indicating which digits we have had so far. So, we have 'digits' = '1010'.
Then, again, n = n / 10 or n = 4.
We shift a '1' again 3 places to the left, getting '1000', and we 'OR' it with digits',
'but since 'digits' already had a '1' in location 4, 'digits' doesn't change:
'1010' OR '1000' = '1010'
and when it detects this, by getting 'digits' = 'digits', the routine knows that it has detected
the same digit more than once, and so n is not a pandigital.
Clever!
But you can achieve the exact same result, by simply using a normal array for this,
and the code will be much easier to follow.
Greetz,
Piet