c++ - 为什么计数整数不返回 d 的预期值?作为数字?

标签 c++ algorithm math codewarrior

我正在处理来自代码 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/

相关文章:

algorithm - 红黑树 - 删除具有两个非叶子节点的节点

algorithm - 二叉树访问: get from one leaf to another leaf

algorithm - A-star是否保证给出二维网格中的最短路径

c++ - 控制台上的不同输出打印标准输出/重定向到文件

algorithm - 销售排名算法

c++ - std::function 到成员函数

c++ - 将 OpenSSL RSA key 与 .Net 结合使用

algorithm - Go:用于字符串比较的多项式指纹

c++ - 虚拟析构函数 : Not Working?

C++获取临时地址 - 将引用分配给指针时出错