Codeforces问题110A-某个输入出现故障



问题:

Petya喜欢幸运数字。我们都知道幸运数字是正整数,其十进制表示只包含幸运数字4和7。例如,数字47、744、4是幸运的,5、17、467不是。

不幸的是,并不是所有的数字都是幸运的。如果一个号码中的幸运数字是一个幸运数字,Petya就会称之为"近乎幸运"。他想知道数字n是否是一个近乎幸运的数字。

输入
唯一一行包含整数n(1≤n≤1018)。

输出
单行打印"是";如果n是一个近乎幸运的数字。否则,打印";否";(没有引号)。

我提交了一个关于这个问题的解决方案,但在4744000695826的输入处失败。这应该给出YES的输出,因为它有4个幸运数字,而4本身就是一个幸运数字。然而,我得到了NO的输出。这是第一个包含4s和7s的输入测试,并且大于32位int极限232-1,所以我想这与此有关,但我真的不知道。

这是我的代码:

#include <iostream>
#include <cmath>
#include <bits/stdc++.h>
#include <cstring>
using namespace std;

// counting digits in an int
int count_digit(int number) {
return int(log10(number) + 1);
}

// counting certain digits in an int
int counter(int b, int n) {
int count = 0;
while(b > 0) {
if(b % 10 == n) {
count++;
}
b /= 10;
}
return count;
}

int main()
{
int k;
cin >> k;
int r = counter(k,4) + counter(k,7);
if (count_digit(r) - (counter(r,4) + counter(r,7)) == 0) {
cout << "YES";
}
else {
cout << "NO";
}
return 0;
}

如果要处理大于int的数字,则需要使用其他方法。

例如,您可以:

std::string number;
std::cin >> number;

然后你可以用检查号码

char value = '5'; 
for(const char& c: number)
{
if (c == value);
}

这样,您甚至不限于64位。

更现代/惯用的方法是使用std::count:

https://en.cppreference.com/w/cpp/algorithm/count

最新更新