How to check if a number is cyclops (number with odd number of digits and zero in the center) in C

2 Answers

0 votes
#include <stdio.h>
#include <stdbool.h>

bool isCyclopsNumber(int n) {
    if (n == 0) {
        return true;
    }

    int m = n % 10;
    int count = 0;
    while (m != 0) {
        count++;
        n /= 10;
        m = n % 10;
    }

    n /= 10;
    m = n % 10;
    while (m != 0) {
        count--;
        n /= 10;
        m = n % 10;
    }

    return n == 0 && count == 0;
}

int main(void) {

    puts(isCyclopsNumber(209) ? "yes" : "no");
    puts(isCyclopsNumber(18037) ? "yes" : "no");
    puts(isCyclopsNumber(5604) ? "yes" : "no");

    return 0;
}




/*
run:

yes
yes
no

*/

 



answered Mar 28, 2023 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool OnlyOneZero(const char* str) {
    int count = 0;
    for (int i = 0; str[i] != 0; i++) {
        if (str[i] == '0') {
            count++;
        }
    }
    return count == 1;
}

bool isCyclopsNumber(int n) {
    if (n == 0) {
        return true;
    }
    
    char str[16] = {0};
    sprintf(str, "%d", n);

    if (!(strlen(str) % 2)) {
        return false;
    }

    if (!OnlyOneZero(str)) {
        return false;
    }

    int mid_index = strlen(str) / 2;
    if (str[mid_index] == '0')
        return true;

    return false;
}

int main(void) {

    puts(isCyclopsNumber(209) ? "yes" : "no");
    puts(isCyclopsNumber(18037) ? "yes" : "no");
    puts(isCyclopsNumber(5604) ? "yes" : "no");

    return 0;
}




/*
run:

yes
yes
no

*/

 



answered Apr 11, 2023 by avibootz
...