Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote