Score a password
The sign-up form shows a strength meter with five segments, one for each rule the password satisfies.
- One point each for: being at least 8 characters, containing a lowercase letter, containing an uppercase letter, containing a digit, and containing anything else.
- The score is therefore between 0 and 5.
passwordScore(password: string) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int passwordScore(std::string password) {
}
Worked examples
| Call | Result |
|---|---|
passwordScore(std::string("abc")) | 1 |
passwordScore(std::string("abcdefgh")) | 2 |
passwordScore(std::string("Abcdefg1")) | 4 |
passwordScore(std::string("Abcdefg1!")) | 5 |
Hint
Five independent booleans, added up. No early returns.
Reference solution in C++
int passwordScore(std::string password) {
bool lower = false, upper = false, digit = false, other = false;
for (char c : password) {
if (c >= 'a' && c <= 'z') lower = true;
else if (c >= 'A' && c <= 'Z') upper = true;
else if (c >= '0' && c <= '9') digit = true;
else other = true;
}
int n = password.size() >= 8 ? 1 : 0;
if (lower) n++;
if (upper) n++;
if (digit) n++;
if (other) n++;
return n;
}