Largest number less than N with digit sum greater than the digit sum of 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.

 Live Demo

#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.

Updated on: 09-Apr-2021

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements