Find a number x such that sum of x and its digits is equal to given n . | CPP program to find x such that x + digSum ( x ) is equal to n . ; utility function for digit sum ; function for finding x ; iterate from 1 to n . For every no . check if its digit sum with it is equal to n . ; if no such i found return - 1 ; driver function
#include <bits/stdc++.h> NEW_LINE 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 ; }