Minimize the sum of digits of A and B such that A + B = N
Last Updated :
01 Mar, 2022
Given an integer N, the task is to find two positive integers A and B such that A + B = N and the sum of digits of A and B is minimum. Print the sum of digits of A and B.
Examples:
Input: N = 16
Output: 7
(10 + 6) = 16 and (1 + 0 + 6) = 7
is minimum possible.
Input: N = 1000
Output: 10
(900 + 100) = 1000
Approach: If N is a power of 10 then the answer will be 10 otherwise the answer will be the sum of digits of N. It is clear that the answer can not be smaller than the sum of digits of N because the sum of digits decreases whenever a carry is generated. Moreover, when N is a power of 10, obviously the answer can not be 1, so the answer will be 10. Because A or B can not be 0 as both of them must be positive numbers.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int minSum( int n)
{
int sum = 0;
while (n > 0) {
sum += (n % 10);
n /= 10;
}
if (sum == 1)
return 10;
return sum;
}
int main()
{
int n = 1884;
cout << minSum(n);
return 0;
}
|
Java
class GFG
{
static int minSum( int n)
{
int sum = 0 ;
while (n > 0 )
{
sum += (n % 10 );
n /= 10 ;
}
if (sum == 1 )
return 10 ;
return sum;
}
public static void main(String[] args)
{
int n = 1884 ;
System.out.print(minSum(n));
}
}
|
Python3
def minSum(n) :
sum = 0 ;
while (n > 0 ) :
sum + = (n % 10 );
n / / = 10 ;
if ( sum = = 1 ) :
return 10 ;
return sum ;
if __name__ = = "__main__" :
n = 1884 ;
print (minSum(n));
|
C#
using System;
class GFG
{
static int minSum( int n)
{
int sum = 0;
while (n > 0)
{
sum += (n % 10);
n /= 10;
}
if (sum == 1)
return 10;
return sum;
}
public static void Main(String[] args)
{
int n = 1884;
Console.Write(minSum(n));
}
}
|
Javascript
<script>
function minSum(n)
{
var sum = 0;
while (n > 0) {
sum += (n % 10);
n = parseInt(n/10);
}
if (sum == 1)
return 10;
return sum;
}
var n = 1884;
document.write( minSum(n));
</script>
|
Time Complexity: O(log n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...