Find a number x such that sum of x and its digits is equal to given n.
Given a positive number n. We need to find a number x such that sum of digits of x to itself is equal to n.
If no such x is possible print -1.
Examples:
Input : n = 21
Output : x = 15
Explanation : x + its digit sum = 15 + 1 + 5 = 21
Input : n = 5
Output : -1
We iterate from 1 to n and for each intermediate number, x find its digit sum and then add that to x, if that is equal to n then x will be our required answer.
// iterate from 1 to n. For every no.
// check if its digit sum with it is
// equal to n.
for (int i = 0; i <= n; i++)
if (i + digSum(i) == n)
return i;
return -1;
C++
#include <bits/stdc++.h>
using namespace std;
int digSum( int n)
{
int sum = 0, rem = 0;
while (n) {
rem = n % 10;
sum += rem;
n /= 10;
}
return sum;
}
int findX( int n)
{
for ( int i = 0; i <= n; i++)
if (i + digSum(i) == n)
return i;
return -1;
}
int main()
{
int n = 43;
cout << "x = " << findX(n);
return 0;
}
|
Java
import java.io.*;
public class GFG
{
static int digSum( int n)
{
int sum = 0 , rem = 0 ;
while (n> 0 ) {
rem = n % 10 ;
sum += rem;
n /= 10 ;
}
return sum;
}
static int findX( int n)
{
for ( int i = 0 ; i <= n; i++)
if (i + digSum(i) == n)
return i;
return - 1 ;
}
public static void main (String[] args)
{
int n = 43 ;
System.out.println( "x = " +findX(n));
}
}
|
Python3
def digSum(n):
sum = 0 ;
rem = 0 ;
while (n):
rem = n % 10 ;
sum = sum + rem;
n = int (n / 10 );
return sum ;
def findX(n):
for i in range (n + 1 ):
if (i + digSum(i) = = n):
return i;
return - 1 ;
n = 43 ;
print ( "x = " , findX(n));
|
C#
using System;
class GFG {
static int digSum( int n)
{
int sum = 0, rem = 0;
while (n > 0)
{
rem = n % 10;
sum += rem;
n /= 10;
}
return sum;
}
static int findX( int n)
{
for ( int i = 0; i <= n; i++)
if (i + digSum(i) == n)
return i;
return -1;
}
public static void Main()
{
int n = 43;
Console.Write( "x = " + findX(n));
}
}
|
PHP
<?php
function digSum( $n )
{
$sum = 0; $rem = 0;
while ( $n )
{
$rem = $n % 10;
$sum += $rem ;
$n /= 10;
}
return $sum ;
}
function findX( $n )
{
for ( $i = 0; $i <= $n ; $i ++)
if ( $i + digSum( $i ) == $n )
return $i ;
return -1;
}
$n = 43;
echo "x = " , findX( $n );
?>
|
Javascript
<script>
function digSum(n)
{
let sum = 0, rem = 0;
while (n>0) {
rem = n % 10;
sum += rem;
n = Math.floor(n / 10);
}
return sum;
}
function findX(n)
{
for (let i = 0; i <= n; i++)
if (i + digSum(i) == n)
return i;
return -1;
}
let n = 43;
document.write( "x = " +findX(n));
</script>
|
Time complexity: O(nlogn) for given input number n
Last Updated :
15 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...