30
Jan
2020

Hackerrank Library Fine (C++)

C++ :

int libraryFine(int d1, int m1, int y1, int d2, int m2, int y2) {
    int fineAmount = 0;

    if(y2 > y1){
        fineAmount = 0;
    }else{
        if(y1 > y2){
            fineAmount = 10000;
        }else if(m1 > m2){
            fineAmount = ((m1 - m2) * 500);
        }else{
            if(m2 > m1){
                fineAmount = 0;
            }else{
                fineAmount = ((d1 - d2) * 15);
            }
        }
    }

    if(fineAmount < 0){
        fineAmount = 0;
    }

    return fineAmount;
}

Explanation:

First, check if y2 is greater than y1. If yes, it means the book was returned at a non expired date, and fineAmount is set to 0.

Else, if the book is a year or more later (y1 greater than y2), fineAmount is fixed at 10,000. Otherwise, the book could be late, but definitely not at least a year late. Check if the book is at least a month late with m1 > m2, if yes, fineAmount is set to (m1 – m2) * 500 per month for fine.

Otherwise, the book is either on time (m2 – m1 is greater than 0), fineAmount is set to 0, or the book is day(s) late. In the final else, after checking if the book is on time with m2 is not greater than m1, the book is day(s) late and the fineAmount is set to (d1 – d2) * 15 per day late.

This does not check if the book is not returned earlier by day(s), so if the final fineAmount is lesser than 0 (book is returned day(s) earlier), the fineAmount is set to 0.

You may also like...

Leave a Reply

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