Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

How to check if a number and its double contain exactly the same digits in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare(const void *a, const void *b) {
    return *(char *)a - *(char *)b;
}

int same_digits_double_number(int n) {
    char str_n[32], str_2n[32];
    
    sprintf(str_n, "%d", n);
    sprintf(str_2n, "%d", 2 * n);
    
    qsort(str_n, strlen(str_n), sizeof(char), compare);
    qsort(str_2n, strlen(str_2n), sizeof(char), compare);
    
    return strcmp(str_n, str_2n) == 0;
}

int main() {
    int n = 125874;

    if (same_digits_double_number(n)) {
        printf("%d and %d contain exactly the same digits", n, 2 * n);
    } else {
        printf("%d and %d do not contain exactly the same digits", n, 2 * n);
    }
    
    return 0;
}



/*
run:

125874 and 251748 contain exactly the same digits

*/

 



answered Jan 29, 2024 by avibootz
0 votes
#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool same_digits_double_number(int number) {
    char dblnumber[32];
    sprintf(dblnumber, "%d", number * 2);
    
    char str_number[32];
    sprintf(str_number, "%d", number);
    
    int count = 0, size = strlen(str_number);
    
    for (int i = 0; i < size; i++) {
        char ch = str_number[i];
        if (strchr(dblnumber, ch) != NULL) {
            count += 1;
        } else {
            return false;
        }
    }
    
    if (count == strlen(str_number)) {
        return true;
    }
}

int main() {
    int n = 125874;
    
    puts(same_digits_double_number(n) ? "yes": "no");
    
    return 0;
}

 
 
 
/*
run:

yes
    
*/

 



answered Mar 5, 2024 by avibootz
...