Write a program that takes an integer and
prints the number of trailing zeroes.
Example:
Enter the number: 24100
Trailing zeroes: 2
I have no Idea what condition to create to determine the number of zeroes in a number.
CodePudding user response:
You could use a modulus trick here:
int input = 24100;
int num_zeroes = 0;
while (input > 0) {
if (input % 10 == 0) {
num_zeroes = num_zeroes 1;
input = input / 10;
}
else {
break;
}
}
printf("%d", num_zeroes); // 2
CodePudding user response:
actually you didn't mention the definition of a trailing zero , but from the definition I found online like here.
In mathematics, trailing zeros are a sequence of 0 in the decimal representation (or more generally, in any positional representation) of a number, after which no other digits follow.
meaning that 12500 has 2 trailing zeros , also 125.50000 has 4 trailing zeros and so on , which means that trailing zero is just number of zeros at the end of the decimals after which no other digit follows , so the easiest way to do is take string from user and compare every character with its ascii representation to find number of consecutive zeros and here the code:
#include <stdio.h>
int main(void)
{
char input_string[100];
printf("enter a number : ");
scanf("%s", &input_string);
int numberOfTrailingZeros = 0;
for (int i = 0; input_string[i] != '\0' ; i) {
if(input_string[i] == '0')
numberOfTrailingZeros ;
else if(input_string[i] == '.')
continue;
else
numberOfTrailingZeros = 0;
}
printf("number of trailing zeros = %d\n", numberOfTrailingZeros);
}