Java Math Exercises: Count the numbers without digit 7, from 1 to a given number
Java Math Exercises: Exercise-18 with Solution
Write a Java program to count the numbers without digit 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:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to calculate and print average of the stream of given numbers.
Next: Write a Java program to generate a magic square of order n.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework