18
Jan
2020

Hackerrank Beautiful Days at the Movies (C++)

C++ :

int beautifulDays(int i, int j, int k) {
    int noOfDays = 0, reverseDay = 0, remainder = 0, day = 0;

    for(; i <= j; i++){
        day = i;
        reverseDay = 0;
        while(day != 0){
            remainder = day % 10;
            reverseDay = (reverseDay * 10) + remainder;
            day /= 10;
        }

        if((reverseDay - i) % k == 0){
            noOfDays++;
        }
    }

    return noOfDays;
}

Explanation:

Using the supplied i and j in the for loop, for each i smaller or equal to j, set day = i and reverseDay = 0. Each number will need to be reversed, eg. 20 into (0)2, 12 into 21 etc.

Taking the 12 to 21 as an example. The while loop reverses them by modding day by 10, then assigning it to the remainder. (remainder is now 2). reverseDay is (0 * 10) + 2 = 2. Integer divide day by 10, day is now 1. Since day is not 0, the while loop continues. Remainder is now 1 % 10 = 1. reverseDay is (2 * 10) + 1 = 21. Integer divide day by 10, day is now 0. Since day is 0, the while loop is completed, and the final value of reverseDay is 21.

The final if statement takes the the difference between reverseDay and i, and mods it by k to check divisibility. If k == 0 (divisible), it is considered a beautiful day, so noOfDays is incremented by 1.

You may also like...

Leave a Reply

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