Minimum Deci-Binary numbers required to obtain a given sum S
Last Updated :
10 Oct, 2023
Given a numeric string S representing a positive decimal integer, the task is to find the minimum number of positive Deci-Binary numbers required to obtain the sum S.
Deci-Binary Numbers: Decimal numbers consisting of only 0s and 1s as its digits.
Examples:
Input: S = “31”
Output: 3
Explanation: S can be represented as the sum of minimum of 3 Deci-Binary numbers {10, 10, 11}.
Input: S = “82734”
Output: 8
Explanation: S can be represented as sum minimum of 8 Deci-Binary numbers {11111, 11111, 10111, 10101, 10100, 10100, 10100, 10000}.
Approach: The given problem can be solved based on the following observations:
Suppose X Deci-Binary numbers are needed to obtain the sum S. To make the sum of X Deci-Binary numbers at i-th place equal to a digit d in S, there must be exactly d Deci-Binary numbers among X numbers having 1 at the ith position.
Therefore, the minimum number of Deci-Binary numbers required to obtain a sum S is equal to the maximum value of any of the digits of S.
Therefore, to solve the problem, iterate over the characters of the string S and find the maximum digit present in it.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minimum_deci_binary_number(string s)
{
int m = INT_MIN;
for ( int i = 0; i < s.size(); i++) {
int temp = s[i] - '0' ;
if (temp > m) {
m = temp;
}
}
return m;
}
int main()
{
string S = "31" ;
cout << minimum_deci_binary_number(S);
return 0;
}
|
Java
class GFG{
static int minimum_deci_binary_number(String s)
{
int m = Integer.MIN_VALUE;
for ( int i = 0 ; i < s.length(); i++)
{
int temp = s.charAt(i) - '0' ;
if (temp > m)
{
m = temp;
}
}
return m;
}
public static void main (String[] args)
{
String S = "31" ;
System.out.println(minimum_deci_binary_number(S));
}
}
|
Python3
def minimum_deci_binary_number(s):
m = - 10 * * 19
for i in range ( len (s)):
temp = ord (s[i]) - ord ( '0' )
if (temp > m):
m = temp
return m
if __name__ = = '__main__' :
S = "31"
print (minimum_deci_binary_number(S))
|
C#
using System;
class GFG
{
static int minimum_deci_binary_number( string s)
{
int m = int .MinValue;
for ( int i = 0; i < s.Length; i++)
{
int temp = s[i] - '0' ;
if (temp > m)
{
m = temp;
}
}
return m;
}
public static void Main (String[] args)
{
string S = "31" ;
Console.WriteLine(minimum_deci_binary_number(S));
}
}
|
Javascript
<script>
function minimum_deci_binary_number(s)
{
let m = Number.MIN_VALUE;
for (let i = 0; i < s.length; i++)
{
let temp = s[i] - '0' ;
if (temp > m)
{
m = temp;
}
}
return m;
}
let S = "31" ;
document.write(minimum_deci_binary_number(S));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...