A common kind of puzzle question is \"how many numbers between 1 and 1000 contai
ID: 3675967 • 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!)
******multiple lines of code*****
Explanation / Answer
Solution:
package com.nancy.chegg.qa;
public class Puzzle {
//Method to compute the count.
public static int countNumsWithDigit(int upperNumber, int digit) {
int count = 0;
for (int i = 1; i <= upperNumber; i++) {
int j = i;
while (j > 0) {
if (j % 10 == digit) {
count++;
break; //Counting only once in any given number, say 22 count one times 2
}
j /= 10;
}
}
return count;
}
public static void main(String[] args) {
int res = countNumsWithDigit(30,2);
System.out.println(res);
}
}
Sample output:
12
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.