我正在处理来自代码 war 的编码问题,但我无法计算它期望从测试值以及他们给你的示例测试中得到的正确答案! 这是提示: "取一个整数n(n >= 0)和一个数字d(0 <= d <= 9)作为一个整数。将0和n之间的所有数字k(0 <= k <= n)平方。计算在所有 k**2 的写入中使用的数字 d。调用 nb_dig(或 nbDig 或...)以 n 和 d 为参数的函数并返回此计数。"
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include<array>
#include<assert.h>
#include<fstream>
using namespace std;
class CountDig
{
public:
static int nbDig(int n, int d);
};
int CountDig::nbDig(int n, int d)
{
int count = 0;
for (int i = 0; i < n; i++)
{
int j = i;
while (j > 0)
{
if (j % 10 == d)
count++;
j /= 10;
}
}
return count;
}
int main()
{
CountDig cnt;
//count.nbDig();
cout << cnt.nbDig(10, 1) << endl;
system("PAUSE");
return 0;
}
用于参数 n 和 d 的示例之一是 nbDig(10,1) 和 nbDig(25,1)。对于 nbDig(10,1),预期答案应该是 4,对于 nbDig(25,1),它应该是 11。
最佳答案
int countDigit( int num, int digit ) {
if( num == 0 && digit == 0 ) return 1; // special case initial condition for 0 and 0
int count = 0;
int j = i;
while (j > 0)
{
if (j % 10 == d)
count++;
j /= 10;
}
return count;
}
关于c++ - 为什么计数整数不返回 d 的预期值?作为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235008/