08
Jan
2020

Hackerrank Grading Students (C++)

C++ :

vector<int> gradingStudents(vector<int> grades) {
    vector<int> roundedGrade(grades.size());
    int gradeToAdd = 0;
    for(int i = 0; i < grades.size(); i++){
        if(grades[i] < 38 || grades[i] % 5 < 3){
            roundedGrade[i] = grades[i];
        }else{
            roundedGrade[i] = grades[i] + (5 - (grades[i] % 5));
        }
    }

    return roundedGrade;
}

Explanation:

As stated in the problem, 38 is the cut off number for rounding, so we’ll go with 38 for the base number instead of having to count from 40.

Modding a number (%) essentially gives the remainder of an integer division, so in the same line of not rounding with a remainder of less than 3, the i th element in grades would not get rounded up, simply toss it to roundedGrade.

Otherwise, rounding occurs, and the number to be added is to make up to the nearest 5, so to get the number to add, use 5 to subtract from the modded remainder.

You may also like...

Leave a Reply

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