Calculate Letter Grade from a Percentage Score

Solve this Problem
Easy10 min
Topics
Companies
Given an integer score between 0 and 100, return the letter grade it earns: "A" for 90 and above, "B" for 80-89, "C" for 70-79, "D" for 60-69, and "F" below 60. The if-else ladderIf-Else LadderA chain of else-if conditions, checked top to bottom, where only the first one that matches actually runs. version is the natural way to express "check the highest threshold first, then the next, then the next." The bucket lookupBucket LookupDividing by a fixed width (10, for 10-point grade bands) to collapse a whole range of scores onto one representative number, then branching on that number instead of the original value. version first reduces the input to a single digit using integer division, then branches on that much smaller space — the same idea used for digit extraction and radix-based problems elsewhere in programming.

Test Case 1:

Input:score = 95
Output:A
Explanation:95 is 90 or above.

Test Case 2:

Input:score = 82
Output:B
Explanation:82 is 80-89.

Test Case 3:

Input:score = 55
Output:F
Explanation:55 is below 60.

Constraints

  • ◆0 ≤ score ≤ 100

Try the Dry Run

Approach & Solutions

If-Else LadderGood

Check the grade boundaries from the top down: 90+ is an A, 80-89 is a B, 70-79 is a C, 60-69 is a D, and anything below 60 is an F. Each condition is only reached once every higher one has already failed, so by the time score >= 80 is checked, score >= 90 is already known to be false.

TimeO(1)
SpaceO(1)
1class Solution { 2 public String calculateGrade(int score) { 3 if (score >= 90) { 4 return "A"; 5 } else if (score >= 80) { 6 return "B"; 7 } else if (score >= 70) { 8 return "C"; 9 } else if (score >= 60) { 10 return "D"; 11 } else { 12 return "F"; 13 } 14 } 15}
Range Division — Bucket LookupOptimal

Instead of comparing score against four separate thresholds, divide it by 10 once to get a single "bucket" number: 95 → 9, 82 → 8, 55 → 5. Every score from 90-100 lands in bucket 9 or 10 (both map to A), 80-89 lands in bucket 8, and so on — so the grade becomes a direct lookup on one computed number instead of a chain of comparisons against score itself.

TimeO(1)
SpaceO(1)
1class Solution { 2 public String calculateGrade(int score) { 3 int bucket = score / 10; 4 if (bucket >= 9) { 5 return "A"; 6 } 7 if (bucket == 8) { 8 return "B"; 9 } 10 if (bucket == 7) { 11 return "C"; 12 } 13 if (bucket == 6) { 14 return "D"; 15 } 16 return "F"; 17 } 18}

Related Problems