Count numbers with difference between number and its digit sum greater than specific value | C ++ program to count total numbers which have difference with sum of digits greater than specific value ; Utility method to get sum of digits of K ; loop until K is not zero ; method returns count of numbers smaller than N , satisfying difference condition ; binary search while loop ; if difference between number and its sum of digit is smaller than given difference then smallest number will be on left side ; if difference between number and its sum of digit is greater than or equal to given difference then smallest number will be on right side ; return the difference between ' smallest ▁ number ▁ ▁ found ' and ' N ' as result ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfDigit ( int K ) { int sod = 0 ; while ( K ) { sod += K % 10 ; K /= 10 ; } return sod ; } int totalNumbersWithSpecificDifference ( int N , int diff ) { int low = 1 , high = N ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( mid - sumOfDigit ( mid ) < diff ) low = mid + 1 ; else high = mid - 1 ; } return ( N - high ) ; } int main ( ) { int N = 13 ; int diff = 2 ; cout << totalNumbersWithSpecificDifference ( N , diff ) ; return 0 ; }