Practice Question 7

Home / Java Practice Question / Practice Question 7

Practice Question 7


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

Program-


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));

}

}