A common kind of puzzle question is \"how many numbers between 1 and 1000 contai
ID: 3676617 • Letter: A
Question
A common kind of puzzle question is "how many numbers between 1 and 1000 contain the digit 7?". Write a function countNumsWithDigit upperNumber, digit) that returns the number of numbers from 1 through upperNumber that contain the given digit. For example countNumsWithDigit(10, 9) should return 1, countNumsWithDigit(10,1) should return 2, and countNumsWithDigit(30, 2) should return 12. Your function must use a list comprehension (but remember, it returns a number not a list!) and have only one line of code (in addition to the def line).Explanation / Answer
import java.util.Scanner;
class GetInputFromUser
{
public static void main(String args[])
{
int un,d;
Scanner in = new Scanner(System.in);
//reading upper number AND DIGIT VALUES
System.out.println("Enter Upper number");
un= in.nextInt();
System.out.println("Enter starting number");
d= in.nextInt();
countNumsWithDigit(un,d);
/* 1 of every 10 numbers contains a 7 ("7")
10 of every 100 numbers contain an additional 7 ("70", "71",...)
100 of every 1000 numbers contain an additional 7 ("700", "701",...)
Number of 7s in 1000
= (1000/10)*1 + (1000/100)*10 + (1000/1000)*100 = 100*1 + 10*10 + 100*1 = 300
Using this logic we can implement the following function*/
int countNumsWithDigit(int uppernumber,int digit)
{
int count=0;
for(int i = 1; i <= uppernumber ; i++)
{
for(char c : String.valueOf(i).toCharArray())
{
if(c == 'digit') count++;
}
return count;
}
}
}//main
}//class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.