华为机试 HJ55 题解 | #挑7#
挑7
https://www.nowcoder.com/practice/ba241b85371c409ea01ac0aa1a8d957b
题目比较简单,从1~n遍历,依次遍历第i个数是否满足以下两个条件中的一个,如果满足其中一个则认为整数i与7相关,计数器加1,代码如下:
#include <iostream>
#include <string>
using namespace std;
int GetRel7Num(int n) {
string str;
int count = 0;
for (int i = 1; i <= n; i++) {
if (i % 7 == 0) {
count++;
continue;
}
str = std::to_string(i);
if (str.find("7") != string::npos) {
count++;
}
}
return count;
}
int main() {
int n;
while (cin >> n) { // 注意 while 处理多个 case
cout << GetRel7Num(n) << endl;
}
}
查看9道真题和解析