美文网首页
【MAC 上学习 C++】Day 61-4. 6-9 统计个位数

【MAC 上学习 C++】Day 61-4. 6-9 统计个位数

作者: RaRasa | 来源:发表于2019-10-24 23:12 被阅读0次

6-9 统计个位数字 (15 分)

1. 题目摘自

https://pintia.cn/problem-sets/14/problems/741

2. 题目内容

本题要求实现一个函数,可统计任一整数中某个位数出现的次数。例如-21252中,2出现了3次,则该函数应该返回3。

函数接口定义:

int Count_Digit ( const int N, const int D );
其中N和D都是用户传入的参数。N的值不超过int的范围;D是[0, 9]区间内的个位数。函数须返回N中D出现的次数。

输入样例:

-21252 2

输出样例:

3

3. 源码参考
#include <iostream>

using namespace std;

int Count_Digit ( const int N, const int D );

int main()
{
    int N, D;

    cin >> N >> D;
    cout << Count_Digit(N, D) << endl;

    return 0;
}

int Count_Digit ( const int N, const int D )
{
  int n;
  int cnt;

  if(N > 0)
  {
    n = N;
  }
  else
  {
    n = -N;
  }

  cnt = 0;
  while(n)
  {
    if(n % 10 == D)
    {
      cnt++;
    }

    n /= 10;
  }

  return cnt; 
}

相关文章

网友评论

      本文标题:【MAC 上学习 C++】Day 61-4. 6-9 统计个位数

      本文链接:https://www.haomeiwen.com/subject/actbmctx.html