Created
March 28, 2021 10:16
-
-
Save gkastrinis/449ad573f53a5884871279e682b46525 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
// num is the original number | |
// i is the current digit | |
// digits is the total number of digits in num | |
// mask is a number with 'digits' length of 1 and 0 | |
void solve(int num, int i, int digits, int mask, int maxOne) { | |
// combine mask and num and print only the digits of num | |
// in the places where mask has 1 | |
if (i == digits) { | |
while (digits--) { | |
if (mask / maxOne) | |
printf("%d", num / maxOne); | |
num %= maxOne; | |
mask %= maxOne; | |
maxOne /= 10; | |
} | |
printf(" "); | |
return; | |
} | |
// Either add another 1 in the mask | |
solve(num, i+1, digits, mask * 10 + 1, maxOne); | |
// or a 0 | |
solve(num, i+1, digits, mask * 10, maxOne); | |
} | |
int main(void) { | |
int NUM = 28408; | |
int t = NUM, digits = 1, maxOne = 1; | |
// calculate num of digits | |
// maxOne == 10^(digits-1) | |
while (t > 9) { | |
digits++; | |
maxOne *= 10; | |
t /= 10; | |
} | |
solve(NUM, 0, digits, 0, maxOne); | |
printf("\n"); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment