题解 | #选牛比赛#
选牛比赛
https://www.nowcoder.com/practice/75df501809d14532a00e747666587873
#include <cstdlib>
#include <string>
class Solution {
public:
int countEligibleCows(vector<string>& digits, int n) {
// write code here
string str_n = to_string(n);
int num_wei = str_n.length(), num_digits = digits.size(), counter = 0;
for (int i = 0; i < num_wei; i++) {
char wei = str_n[i];
int j = 0;
while (j < num_digits) {
if (digits[j][0] >= wei) {
break;
}
j++;
}
if (num_wei - i - 1 != 0) {
counter += (j + 1) * pow(num_digits, num_wei - i - 1);
}
// 如果数组中的所有元素都大于当前位的值,则计算后面位数的排列组合并返回。如果等于则进入下一次循环
if (j < num_digits && digits[j][0] > wei) {
for (int k = i + 1; k < num_wei; k++) {
if (num_wei - k - 1 != 0) {
counter += pow(num_digits, num_wei - k - 1);
}
}
break;
}
}
return counter;
}
};