【问题标题】:Why doesn't the count integer return the expected value of d? as in digit?为什么 count 整数不返回 d 的期望值?如数字?
【发布时间】:2017-05-29 05:13:57
【问题描述】:

我正在处理代码大战中的一个编码问题,但我无法从测试值以及它们给你的示例测试中计算出它期望的正确答案! 这是提示: “取一个整数 n (n >= 0) 和一个数字 d (0

#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。

【问题讨论】:

  • nbDig()static。为什么要通过对象调用它?
  • 你明白为什么正确答案分别是 4 和 11 吗? (如果不是,则意味着您不了解您应该编码的内容,因此您没有成功的希望)。
  • int j = i; --> int j = i * i; , i &lt; n --> i &lt;= n
  • 是的,因为 n 表示数字以及 d 表示我们正在计数的指定数字,所以在调用 nbDig(10,1) 的情况下,有 10 个整数被计算出然后平方,但指定的要计数的数字是 1,因此所有带有“1”的整数都应该被计算在内。好的,现在我知道我在哪里搞砸了,我需要在计算数字之前合并数字的平方-_-
  • 我已经修复了它们,现在它确实是一个 -_-

标签: c++ algorithm math codewarrior


【解决方案1】:
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;
}

【讨论】:

  • 虽然我确实看到了你所说的,但输出仍然是一样的,并没有真正改变程序的任何内容
猜你喜欢
  • 1970-01-01
  • 2016-11-22
  • 2021-05-04
  • 2021-02-01
  • 2014-06-05
  • 2013-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多