Imagine we've got an int number = 1040 or int number = 105 in a C program, and we want to know if this number contains a 0 and in which position/s are they. How could we do it?

Examples

1040 -> position 0 and 2.

1000 -> position 0, 1 and 2.

104 -> position 1.

56 -> NO ZEROS.

Thanks!

有帮助吗?

解决方案 2

I would convert it to a string; finding a character in a string is trivial.

As a rule of thumb, if you are doing maths on something, it's a number; otherwise, it's probably (or should be treated as) a string.

Alternatively, something like:

#include <stdio.h>

int main(void) {
    int input=1040;
    int digitindex;
    for (digitindex=0; input>0; digitindex++) {
        if (input%10==0) {
            printf("0 in position %i\n",digitindex);
        }
        input/=10;
    }
    return 0;
}

This basically reports if the LAST digit is 0, then removes the last digit; repeat until there is nothing left. Minor modifications would be required for negative numbers.

You can play with this at http://ideone.com/oEyD7N

其他提示

I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10

#include<iostream>   

int main(void)
{
long int k = 6050404;
int iter = 0;
while (k > 10) {
    long int r = k % 10;
    if( r == 0) {
        std::cout << iter << " ";
    }
    k = k / 10;
    iter++;
}
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top