Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print numbers with digits 0 and 1 only such that their sum is N in C Program.
Given an integer n, the task is to print numbers consisting only of digits 0 and 1 whose sum equals n. The valid numbers containing only zeros and ones are: 1, 10, 11, 100, 101, 110, 111, etc. We need to find a combination of these numbers that adds up to n.
For example, if n = 31, possible combinations are: 10+10+11 = 31 or 10+10+10+1 = 31.
Syntax
void findNumbers(int n);
Algorithm
The algorithm uses a greedy approach −
- Start with the given number n
- While n > 0, check if we can subtract 10 (when n > 20)
- If n equals 11, subtract 11
- Otherwise, subtract 1
Example
#include <stdio.h>
// Function to find and print numbers
void findNumbers(int n) {
int a = n;
printf("Numbers that sum to %d: ", n);
while(a > 0) {
if(a / 10 > 0 && a > 20) {
a = a - 10;
printf("10 ");
}
else if(a == 11) {
a = a - 11;
printf("11 ");
}
else {
printf("1 ");
a--;
}
}
printf("<br>");
}
int main() {
int N = 35;
printf("Input: %d<br>", N);
findNumbers(N);
// Test with another value
N = 31;
printf("\nInput: %d<br>", N);
findNumbers(N);
return 0;
}
Input: 35 Numbers that sum to 35: 10 10 10 1 1 1 1 1 Input: 31 Numbers that sum to 31: 10 10 11
How It Works
The algorithm prioritizes larger valid numbers first −
- Step 1: If the remaining sum is greater than 20, subtract 10
- Step 2: If the remaining sum exactly equals 11, subtract 11
- Step 3: Otherwise, subtract 1
Key Points
- The algorithm uses a greedy approach to minimize the count of numbers
- Valid numbers are: 1, 10, 11 (and their larger combinations)
- Time complexity: O(n) in worst case
- Space complexity: O(1)
Conclusion
This greedy algorithm efficiently finds numbers containing only digits 0 and 1 that sum to a given value. It prioritizes using larger valid numbers to minimize the total count of numbers in the solution.
Advertisements
