w3resource

Java: Count the numbers without digit 7, from 1 to a given number


Count Numbers Without 7

Write a Java program to count numbers without 7 from 1 to a given number.

Sample Solution:

Java Code:

import java.util.*;
class solution { 
    static int count_nums_not_7(int num) 
    { 
        if (num < 7) 
            return num; 
        if (num >= 7 && num < 10) 
            return num-1; 
 
        int r = 1; 
        while (num/r > 9) 
            r = r*10; 
  
        int m = num/r; 
   
        if (m != 7) 
            return count_nums_not_7(m)*count_nums_not_7(r - 1) + count_nums_not_7(m) + count_nums_not_7(num%r); 
        else
            return count_nums_not_7(m*r - 1); 
    } 
  
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Input a number: ");
        int num = scan.nextInt();
		if (num>0)
		System.out.println("Count the numbers without digit 7, from 1 to "+num+": "+count_nums_not_7(num));		
		}
}

Sample Output:

 Input a number:  15
Count the numbers without digit 7, from 1 to 15: 14

Flowchart:

Flowchart: Count the numbers without digit 7, from 1 to a given number.



For more Practice: Solve these Related Problems:

  • Write a Java program to recursively count numbers from 1 to n that do not contain the digit 7.
  • Write a Java program to filter out numbers containing the digit 7 from a range using Java streams.
  • Write a Java program to iterate over a range and count numbers lacking the digit 7 using string pattern matching.
  • Write a Java program to implement a function that checks if a number contains digit 7 and use it to count valid numbers.

Go to:


PREV : Stream Average Calculation.
NEXT : Generate Magic Square.


Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.