20
Jan
2020

Hackerrank Find Digits (C++)

C++ :

int findDigits(int n) {
    int divisorNo = 0, nHolder = n, divisor = 0;
    
    while(nHolder != 0){
        divisor = nHolder % 10;
        nHolder /= 10;
        if(divisor != 0){
            if(n % divisor == 0){
            divisorNo++;
            }
        }  
    }

    return divisorNo;
}

Explanation:

This question basically deals with getting individual digits from a number with mod (%) and integer division.

In the while loop, we will loop till nHolder (temporary holder for n) becomes 0. The divisor is assigned to nHolder % 10, and this will allow divisor to hold each digit in a number (eg. 5, 4, 3, 2, 1 from 12345), starting from the number at the back. Integer divide nHolder by 10 to shift bits right to “push” the second last number to the last position.

The if checks if divisor is a factor of n, if it is, increment divisorNo by 1.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *