Need a code that counts the same digit in a number

前端 未结 2 1847
旧巷少年郎
旧巷少年郎 2021-01-29 17:12

As title says , need a code that counts the same digit in a number..

For example:

If I put 54678, it shows me how many number 5 is used in that integer.

相关标签:
2条回答
  • 2021-01-29 17:23

    You can enter the number as a string and then parse the string.

    0 讨论(0)
  • 2021-01-29 17:26

    You could use a function like this, where n is the number and d is the digit you want to count:

    int count_dig(int n, int d) {
        int result = 0;
        while (n > 0) {
            if (n % 10 == d) {
                result++;
            }
            n/=10;
        }
        return result;
    }
    

    Using this, you could print your formatted result like:

    printf("%d -- You used digit %d %d times.", n, d, count_dig(n, d));
    
    0 讨论(0)
提交回复
热议问题