
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Number X Where Sum of X and Its Digits Equals 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
#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
Advertisements