Find a number x such that sum of x and its digits is equal to given n using C++.

Here we will see one problem, where we take a number n, we have to find another value say x, such that x + digit sum of x is same as the given number n. Suppose the value of n is 21. This program will return a number x = 15, as 15 + digit sum of 15, i.e. 15 + 1 + 5 = 21 = n.

To solve this problem, we have to follow simple approach. We will iterate through 1 to n, in each iteration, we will see if the sum of the number and its digit sum is same as the number, then stop, otherwise continue.

Example

Live Demo

#include<iostream>
using namespace std;
int getDigitSum(int n) {
int sum = 0;
while (n) {
sum += n % 10;
n /= 10;
}
return sum;
}
int getNumber(int n) {
for (int i = 0; i <= n; i++)
if (i + getDigitSum(i) == n)
return i;
return -1;
}
int main() {
int n = 21;
cout << "The value of x is: " << getNumber(n);
}

Output

The value of x is: 15

Updated on: 29-Oct-2019

71 Views

Get certified by completing the course