题解 | #挑7#
挑7
https://www.nowcoder.com/practice/ba241b85371c409ea01ac0aa1a8d957b
#include <iostream>
using namespace std;
class Pick7 {
private:
//上限
int n;
public:
//构造函数
Pick7(const int n);
//析构函数
~Pick7();
//判断正整数i是否与7有关
bool judge(const int i)const;
//不大于n的数中与7有关的正整数的个数
int count(void)const;
};
Pick7::Pick7(const int n) {
this->n = n;
return;
}
Pick7::~Pick7() {
}
bool Pick7::judge(const int i) const {
//如果i是7的倍数
if (i % 7 == 0)
return true;
//如果i的个位是7
if (i % 10 == 7)
return true;
//如果i>10
if (i > 10) {
int j = i / 10;
//如果i的十位是7
if (j % 10 == 7)
return true;
//如果i>100
if (j > 10) {
int k = j / 10;
//如果i的百位是7
if (k % 10 == 7)
return true;
//如果i>1000
if (k > 10) {
int l = k / 10;
//如果i的千位是7
if (l % 10 == 7)
return true;
//由于上限为3万,不考虑万位是7(以及更高位是7)的情况
}
}
}
return false;
}
int Pick7::count(void) const {
//穷举、判断、计数
int num = 0;
for (int i = 1; i <= this->n; i++)
if (this->judge(i))
num++;
return num;
}
int main() {
int a;
while (cin >> a) { // 注意 while 处理多个 case
cout << Pick7(a).count() << endl;
}
}
// 64 位输出请用 printf("%lld")
查看1道真题和解析