首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >查找整数中出现的数字

查找整数中出现的数字
EN

Stack Overflow用户
提问于 2015-02-22 04:25:07
回答 1查看 2.7K关注 0票数 2

伙计们,我有一个问题,要创建一个函数来计算整数中一个数字的出现。我创建了2 int,int n,其中包含0到9之间的值,其中int值是一个数字,最多可达9位数。我必须创建一个函数countOccurence来计算每个数字在我输入的值中发生了多少次。例如,如果我输入"12345",则1 2 3 4 5发生一次,而6 7 8 9 0发生0次。我试过了但被卡住了。

这就是我到目前为止所得出的结论,我只是想不出答案。

代码语言:javascript
复制
#include <iostream>
using namespace std;

int main()
{
    int countOccurance(int, int);
    int findDig(int);

    int value;
    int n = 0;

    cout << "Please enter a positive number: " << endl;
    cin >> value;
    cout << "The value is " << value << endl;

    while ((value < 0) || (value > 999999999))
    {
        cout << "Invalid value. Please try again!" << endl;
        cout << "Please enter a positive number: " << endl;
    }

    //process the value

}

int countOccurance(int findDig, int value)
{

}

谢谢你的帮助,我真的很感激

EN

回答 1

Stack Overflow用户

发布于 2015-02-22 04:43:26

这样的东西应该能给你你想要的东西。

代码语言:javascript
复制
int findDig(int n) 
{
    if (n < 10)
        return 1;
    else 
       return 1 + findDig(n / 10);
}

int countOccurance(int value)
{
    for(int i = 0 ; i < 10 ; i++)
    {
        int val = value;
        int count = 0;
        while(val > 0)
        {
            if(val % 10 == i)
                count ++;
            val /= 10;
        }
        cout << count << " occourences of " << i << endl;
    }
}

int main()
{
    int value;
    int n = 0;

    cout << "Please enter a positive number: " << endl;
    cin >> value;
    cout << "The value is " << value << endl;

    while ((value < 0) || (value > 999999999))
    {
        cout << "Invalid value. Please try again!" << endl;
        cout << "Please enter a positive number: " << endl;
        cin >> value //you need this here, otherwise you're going to be stuck in an infinite loop after the first invalid entry
    }

    //process the value

    cout << endl;
    cout << "This " << value << " number is a " << findDig(value) << " digit integer number." << endl;

    cout << "Digit counts" << endl;

    countOccourance(value);
}

编辑

如果您需要countOccourence来返回一个值,就应该这样做。

代码语言:javascript
复制
int countOccourence(int dig, int val)
{
    if(n > 0)
    {
        return countOccourence(dig, val / 10) + (val % 10 == dig);
    }
    else
        return 0;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28654545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档