Count numbers from 1 to n that have 4 as a digit | Java program to compute sum of digits in numbers from 1 to n ; Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program
import java . io . * ; class GFG { static int countNumbersWith4 ( int n ) { int result = 0 ; for ( int x = 1 ; x <= n ; x ++ ) result += has4 ( x ) ? 1 : 0 ; return result ; } static boolean has4 ( int x ) { while ( x != 0 ) { if ( x % 10 == 4 ) return true ; x = x / 10 ; } return false ; } public static void main ( String args [ ] ) { int n = 328 ; System . out . println ( " Count ▁ of ▁ numbers ▁ from ▁ 1 ▁ to ▁ " + " ▁ that ▁ have ▁ 4 ▁ as ▁ a ▁ a ▁ digit ▁ is ▁ " + countNumbersWith4 ( n ) ) ; } }