Given a number N, the task is to find the required numbers consist of only 0 and 1 digit whose sum is equal to N.
Example:
Input: 9
Output: 1 1 1 1 1 1 1 1 1
Only numbers smaller than or equal to 9 with
digits 0 and 1 only are 0 and 1 itself.
So to get 9, we have to add 1 - 9 times.
Input: 31
Output: 11 10 10
Approach:
- Initialize product p to 1 and m to zero.
- Create the vector that stores the resultant integer counts of 0s and 1s.
- Loop for N and check if N is multiple of 10 if yes get the decimal and update p by multiplying 10 and store this value in a vector and decrease N by m do this for each decimal and print the total size of vector.
- Finally traverse the vector and print the elements.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findNumbers( int N)
{
vector< int > v;
while (N) {
int n = N, m = 0, p = 1;
while (n) {
if (n % 10)
m += p;
n /= 10;
p *= 10;
}
v.push_back(m);
N -= m;
}
for ( int i = 0; i < v.size(); i++)
cout << " " << v[i];
return 0;
}
int main()
{
int N = 31;
findNumbers(N);
return 0;
}
|
Java
import java.util.*;
public class GfG{
public static int findNumbers( int N)
{
ArrayList<Integer> v = new ArrayList<Integer>();
while (N > 0 ) {
int n = N, m = 0 , p = 1 ;
while (n > 0 ) {
if (n % 10 != 0 )
m += p;
n /= 10 ;
p *= 10 ;
}
v.add(m);
N -= m;
}
for ( int i = 0 ; i < v.size(); i++)
System.out.print( " " + v.get(i));
return 0 ;
}
public static void main(String []args){
int N = 31 ;
findNumbers(N);
}
}
|
Python3
def findNumbers(N) :
v = [];
while (N) :
n, m, p = N, 0 , 1
while (n) :
if (n % 10 ) :
m + = p
n / / = 10
p * = 10
v.append(m);
N - = m
for i in range ( len (v)) :
print (v[i], end = " " )
if __name__ = = "__main__" :
N = 31
findNumbers(N)
|
C#
using System;
using System.Collections;
class GfG
{
public static int findNumbers( int N)
{
ArrayList v = new ArrayList();
while (N > 0)
{
int n = N, m = 0, p = 1;
while (n > 0)
{
if (n % 10 != 0)
m += p;
n /= 10;
p *= 10;
}
v.Add(m);
N -= m;
}
for ( int i = 0; i < v.Count; i++)
Console.Write( " " + v[i]);
return 0;
}
public static void Main()
{
int N = 31;
findNumbers(N);
}
}
|
PHP
<?php
function findNumbers( $N )
{
$v = array ();
while ( $N )
{
$n = $N ;
$m = 0;
$p = 1;
while ( $n )
{
if ( $n % 10)
$m += $p ;
$n /= 10;
$p *= 10;
}
array_push ( $v , $m );
$N -= $m ;
}
for ( $i = 0; $i < sizeof( $v ); $i ++)
echo " " , $v [ $i ];
return 0;
}
$N = 31;
findNumbers( $N );
?>
|
Javascript
<script>
function findNumbers(N)
{
let v = [];
while (N) {
let n = N, m = 0, p = 1;
while (n) {
if (n % 10)
m += p;
n = parseInt(n/10);
p *= 10;
}
v.push(m);
N -= m;
}
for (let i = 0; i < v.length; i++)
document.write( " " + v[i]);
return 0;
}
let N = 31;
findNumbers(N);
</script>
|
Complexity Analysis:
- Time Complexity: O(log(N))
- Auxiliary Space: O(log(N)), since log(N) extra space has been taken.