简体   繁体   中英

Count how many of a certain digit is present on a given number in C

Using a while loop, i need count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.

input sample: 2, 124218

output sample: 2

this is my code below:

#include<stdio.h>
int main() {
    int a;
    int num; 
    int i;
    int rev = 0;
    int reminder;
    int count = 1;
    int ans;
    int last;

    scanf("%d",&a);
    scanf("%d", &num );

    while(num!=0)
    {
        reminder=num%10;
        rev=rev*10+reminder;
        num/=10;

        if(a==reminder){
            ans++; 

            last = ans%10;
    
            printf("%d", last);
        }
        count++; 
    }
    return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main() {
int a, num, remainder, count = 0;

scanf("%d",&a);
scanf("%d",&num );
int temp = abs(num);
while(temp!=0)
{
    remainder=temp%10;
    temp/=10;
    if(a==remainder)
        count++; 
}
printf("%d",count);
return 0;
}
int count_digit(const unsigned digit, int number)
{
    int count = 0;
    if(digit < 10)
    {
        while(number)
        {
            if(digit == abs(number % 10)) count++;
            number /= 10;
        }
    }
    else
    {
        count = -1;  //error 
    }
    return count;
}

int main(void)
{
    printf("%d\n", count_digit(5, 455675));
    printf("%d\n", count_digit(3, -35633435));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM