
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 a Number X Whose Sum with Its Digits Equals N in C++
In this tutorial, we are going to find a number whose some including with its digits is equal to the given number N.
The idea is simple, we are going to check the left and right 100 numbers of the given number. It won't lie out that bound as N ≤ 1000000000 and the sum won't exceed 100.
Let's see the steps to solve the problem.
Initialize the number.
-
Write a loop that iterates 100 times.
Get the n - i and n + i values.
Find the sum of the digits and add them.
If anyone of them is equal to the N, print them.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; int digitsSum(int n) { int sum = 0; while (n) { sum += n % 10; n /= 10; } return sum; } void findX(long int n) { bool is_found = false; for (int i = 0; i <= 100; i++) { long int valueOnLeft = abs(n - i) + digitsSum(abs(n - i)); long int valueOnRight = n + i + digitsSum(n + i); if (valueOnLeft == n) { is_found = true; cout << abs(n - i) << " "; } if (valueOnRight == n) { is_found = true; cout << (n + i) << " "; } } if (!is_found) { cout << "No numbers found"; } cout << endl; } int main() { int n = 89; findX(n); return 0; }
Output
If you execute the above program, then you will get the following result.
76
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements