
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
Largest Number Less Than N with Digit Sum Greater Than N in C++
In this tutorial, we are going to write a program that finds the number less than N with digit sum greater than the digit sum of n.
Let's see the steps to solve the problem.
- Write a function to find the digits sum.
- Initialise n.
- Write a loop that iterates from n - 1 to 1.
- Check the digits sum of current number with the digits sum of n.
- If the digits sum of current number is greater than n, then return the current number.
- Move to the next number.
Example
Let's see the code.
#include <bits/stdc++.h> using namespace std; int sumOfDigits(int n) { int digitsSum = 0; while (n > 0) { digitsSum += n % 10; n /= 10; } return digitsSum; } int findLargestNumber(int n) { int i = n - 1; while (i > 0) { if (sumOfDigits(i) > sumOfDigits(n)) { return i; } i--; } return -1; } int main() { int n = 75; cout << findLargestNumber(n) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
69
Conclusion
If you have any queries in the tutorial, mention them in the comment section.
Advertisements