Write computer program to calculate number of occurrences of digit 7 in 1-1000 series. in java

This page contains a sample solution to one of the exercises from Introduction to Programming Using Java.

Exercise 2.2:

Write a program that simulates rolling a pair of dice. You can simulate rolling one die by choosing one of the integers 1, 2, 3, 4, 5, or 6 at random. The number you pick represents the number on the die after it is rolled. As pointed out in Section 2.5, the expression

(int)(Math.random()*6) + 1

does the computation to select a random integer between 1 and 6. You can assign this value to a variable to represent one of the dice that are being rolled. Do this twice and add the results together to get the total roll. Your program should report the number showing on each die as well as the total roll. For example:

The first die comes up 3 The second die comes up 5 Your total roll is 8

Discussion

When designing a program, one of the first things you should ask yourself is, "What values do I need to represent?" The answer helps you decide what variables to declare in the program. This program will need some variables to represent the numbers showing on each die and the total of the two dice. Since these numbers are all integers, we can use three variables of type int. I'll call the variables die1, die2, and roll. The program begins by declaring the variables:

int die1; int die2; int roll;

In the actual program, of course, I've added a comment to explain the purpose of each variable. The values of die1 and die2 can be computed using the expression given in the exercise:

die1 = (int)(Math.random()*6) + 1; die2 = (int)(Math.random()*6) + 1;

Note that even though the expressions on the right-hand sides of these assignment statements are the same, the values can be different because the function Math.random() can return different values when it is called twice.

We can then compute roll = die1 + die2 and use three System.out.println statements to display the three lines of output:

System.out.println("The first die comes up " + die1); System.out.println("The second die comes up " + die2); System.out.println("Your total roll is " + roll);

Note that I've chosen to use the concatenation operator, +, to append the value of die1 onto the string "The first die comes up". Alternatively, I could use two output statements:

System.out.print("The first die comes up "); System.out.println(die1);

Yet another possibility is to use System.out.printf:

System.out.printf("The first die comes up %d%n", die1);

I'll also note that I could get away without the variable roll, since I could output the value of the expression die1 + die2 directly:

System.out.println("Your total roll is " + (die1 + die2));

However, it's generally better style to have a meaningful name for a quantity. By the way, the parentheses around (die1 + die2) are essential because of the precedence rules for the + operator. You might try to experiment with leaving them out and see what happens.

As a final variation, all three lines of output could be produced using a multiline text block. Text blocks were discussed in Subsection 2.3.4. Using a text block also requires System.out.printf:

System.out.printf(""" The first die comes up %d The second die comes up %d Your total roll is %d """, die1, die2, roll);

The Solution

public class RollTheDice { /* This program simulates rolling a pair of dice. The number that comes up on each die is output, followed by the total of the two dice. */ public static void main(String[] args) { int die1; // The number on the first die. int die2; // The number on the second die. int roll; // The total roll (sum of the two dice). die1 = (int)(Math.random()*6) + 1; die2 = (int)(Math.random()*6) + 1; roll = die1 + die2; System.out.println("The first die comes up " + die1); System.out.println("The second die comes up " + die2); System.out.println("Your total roll is " + roll); } // end main() } // end class

public class Main { public static void main(String[] args) { int count = 0, num = 0003452; while (num != 0) { // num = num/10 num /= 10; ++count; } System.out.println("Number of digits: " + count); } }

Output

Number of digits: 4

In this program, while the loop is iterated until the test expression num != 0 is evaluated to 0 (false).

  • After the first iteration, num will be divided by 10 and its value will be 345. Then, the count is incremented to 1.
  • After the second iteration, the value of num will be 34 and the count is incremented to 2.
  • After the third iteration, the value of num will be 3 and the count is incremented to 3.
  • After the fourth iteration, the value of num will be 0 and the count is incremented to 4.
  • Then the test expression is evaluated to false and the loop terminates.

Note: The program ignores any zero's present before the number. Hence, for digits like 000333, the output will be 3.

Example 2: Count Number of Digits in an Integer using for loop

public class Main { public static void main(String[] args) { int count = 0, num = 123456; for (; num != 0; num /= 10, ++count) { } System.out.println("Number of digits: " + count); } }

Output

Number of digits: 6

In this program, instead of using a while loop, we use a for loop without any body.

On each iteration, the value of num is divided by 10 and count is incremented by 1.

The for loop exits when num != 0 is false, i.e. num = 0.

Since, for loop doesn't have a body, you can change it to a single statement in Java as such:

for(; num != 0; num/=10, ++count);

Given a number N and a digit D, the task is to count the occurrences of D in N.
Examples: 
 

Input: N = 25, D = 2 Output: 1 Input: N = 100, D = 0 Output: 2

Approach: Take out the digits one by one in N and check if this digit is equal to D. If equal, then increment the count by 1. In the end, print the count.Below is the implementation of the above approach: 

long long int countoccurrences(long long int n,

    long long int n = 214215421;

    cout << countOccurrances(n, d)

static int countoccurrences(int n,

public static void main(String args[])

    System.out.println(countOccurrances(n, d));

def countoccurrences(n, d):

print(countOccurrances(n, d))

static int countoccurrences(int n,

public static void Main()

    Console.WriteLine(countOccurrances(n, d));

function countoccurrences(n, d)

    document.write(countOccurrances(n, d));


Article Tags :

Count the number of 2s as digit in all numbers from 0 to n. 

Examples : 

Input : 22 Output : 6 Explanation: Total 2s that appear as digit from 0 to 22 are (2, 12, 20, 21, 22); Input : 100 Output : 20 Explanation: total 2's comes between 0 to 100 are (2, 12, 20, 21, 22..29, 32, 42, 52, 62, 72, 82, 92);

A Simple Brute force solution is to iterate through all numbers from 0 to n. For every number being visited, count the number of 2’s in it. Finally return total count.

Below is implementation of the idea.  

int numberOf2sinRange(int n)

    for (int i = 2; i <= n; i++)

    cout << numberOf2sinRange(22);

    cout << numberOf2sinRange(100);

static int number0f2s(int n)

static int numberOf2sinRange(int n)

    for (int i = 2; i <= n; i++)

public static void main(String[] args)

    System.out.print(numberOf2sinRange(22));

    System.out.print(numberOf2sinRange(100));

def numberOf2sinRange(n):

    for i in range(2, n + 1):

        count = count + number0f2s(i)

print(numberOf2sinRange(22))

print(numberOf2sinRange(100))

static int number0f2s(int n)

static int numberOf2sinRange(int n)

    for (int i = 2; i <= n; i++)

public static void Main()

    Console.Write(numberOf2sinRange(22));

    Console.Write(numberOf2sinRange(100));

function numberOf2sinRange($n)

    for ($i = 2; $i <= $n; $i++)

        $count += number0f2s($i);

    echo (numberOf2sinRange(22));

    echo numberOf2sinRange(100);

            n = parseInt(n / 10, 10);

    function numberOf2sinRange(n)

        for (let i = 2; i <= n; i++)

    document.write(numberOf2sinRange(22) + "</br>");

    document.write(numberOf2sinRange(100));

Below is an alternate implementation of this approach.

int numberOf2sinRange(int n)

    for(int i = 0; i < n + 1; i++)

    for(int i = 0; i < s.length(); i++)

    cout << numberOf2sinRange(n);

  static int numberOf2sinRange(int n)

    for(int i = 0; i < n + 1; i++)

    for(int i = 0; i < s.length(); i++)

  public static void main(String[] args) {

    System.out.println(numberOf2sinRange(n));

def numberOf2sinRange(n):

    return(list(s).count('2'))

print(numberOf2sinRange(n))

  static int numberOf2sinRange(int n)

    for(int i = 0; i < n + 1; i++)

    for(int i = 0; i < s.Length; i++)

  public static void Main(string[] args)

    Console.Write(numberOf2sinRange(n));

function numberOf2sinRange(n)

    for(var i = 0; i < n + 1; i++)

    for(var i = 0; i < s.length; i++)

document.write(numberOf2sinRange(n));

Improved Solution 
The idea is to look at the problem digit by digit. Picture a sequence of numbers: 

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ...... 110 111 112 113 114 115 116 117 118 119

We know that roughly one tenth of the time, the last digit will be a 2 since it happens once in any sequence of ten numbers. In fact, any digit is a 2 roughly one tenth of the time. 

We say “roughly” because there are (very common) boundary conditions. For example, between 1 and 100, the 10’s digit is a 2 exactly 1/10th of the time. However, between 1 and 37, the 10’s digit is a 2 much more than 1/10th of the time. 
We can work out what exactly the ratio is by looking at the three cases individually: digit 2. 

Case digits < 2 
Consider the value x = 61523 and digit at index d = 3 (here indexes are considered from right and rightmost index is 0). We observe that x[d] = 1. There are 2s at the 3rd digit in the ranges 2000 – 2999, 12000 – 12999, 22000 – 22999, 32000 32999, 42000 – 42999, and 52000 – 52999. So there are 6000 2’s total in the 3rd digit. This is the same amount as if we were just counting all the 2s in the 3rd digit between 1 and 60000.

In other words, we can round down to the nearest 10d+1, and then divide by 10, to compute the number of 2s in the d-th digit.  

if x[d) < 2: count2sinRangeAtDigit(x, d) = Compute y = round down to nearest 10d+1 return y/10

Case digit > 2 
Now, let’s look at the case where d-th digit (from right) of x is greater than 2 (x[d] > 2). We can apply almost the exact same logic to see that there are the same number of 2s in the 3rd digit in the range 0 – 63525 as there as in the range 0 – 70000. So, rather than rounding down, we round up.

if x[d) > 2: count2sinRangeAtDigit(x, d) = Compute y = round down to nearest 10d+1 return y / 10

Case digit = 2 
The final case may be the trickiest, but it follows from the earlier logic. Consider x = 62523 and d = 3. We know that there are the same ranges of 2s from before (that is, the ranges 2000 – 2999, 12000 – 12999, … , 52000 – 52999). How many appear in the 3rd digit in the final, partial range from 62000 – 62523? Well, that should be pretty easy. It’s just 524 (62000, 62001, … , 62523). 

if x[d] = 2: count2sinRangeAtDigit(x, d) = Compute y = round down to nearest 10d+1 Compute z = right side of x (i.e., x% 10d) return y/10 + z + 1

Now, all we need is to iterate through each digit in the number. Implementing this code is reasonably straightforward. 

Below is the implementation of the idea.

int count2sinRangeAtDigit(int number, int d)

    int powerOf10 = (int)pow(10, d);

    int nextPowerOf10 = powerOf10 * 10;

    int right = number % powerOf10;

    int roundDown = number - number % nextPowerOf10;

    int roundup = roundDown + nextPowerOf10;

    int digit = (number / powerOf10) % 10;

        return roundDown / 10 + right + 1;

int numberOf2sinRange(int number)

    string s = convert.str();

    for (int digit = 0; digit < len; digit++)

        count += count2sinRangeAtDigit(number, digit);

    cout << numberOf2sinRange(22) << endl;

    cout << numberOf2sinRange(100);

    static int count2sinRangeAtDigit(int number, int d)

        int powerOf10 = (int) Math.pow(10, d);

        int nextPowerOf10 = powerOf10 * 10;

        int right = number % powerOf10;

        int roundDown = number - number % nextPowerOf10;

        int roundup = roundDown + nextPowerOf10;

        int digit = (number / powerOf10) % 10;

            return roundDown / 10 + right + 1;

    static int numberOf2sinRange(int number)

        convert = String.valueOf(number);

        for (int digit = 0; digit < len; digit++)

            count += count2sinRangeAtDigit(number, digit);

    public static void main(String[] args)

        System.out.println(numberOf2sinRange(22));

        System.out.println(numberOf2sinRange(100));

def count2sinRangeAtDigit(number, d):

    powerOf10 = int(pow(10, d));

    nextPowerOf10 = powerOf10 * 10;

    right = number % powerOf10;

    roundDown = number - number % nextPowerOf10;

    roundup = roundDown + nextPowerOf10;

    digit = (number // powerOf10) % 10;

        return roundDown // 10 + right + 1;

def numberOf2sinRange(number):

    for digit in range(len1):

        count += count2sinRangeAtDigit(number,

print(numberOf2sinRange(22));

print(numberOf2sinRange(100));

static int count2sinRangeAtDigit(int number,

    int powerOf10 = (int) Math.Pow(10, d);

    int nextPowerOf10 = powerOf10 * 10;

    int right = number % powerOf10;

    int roundDown = number - number % nextPowerOf10;

    int roundup = roundDown + nextPowerOf10;

    int digit = (number / powerOf10) % 10;

        return roundDown / 10 + right + 1;

static int numberOf2sinRange(int number)

    convert = number.ToString();

    for (int digit = 0; digit < len; digit++)

        count += count2sinRangeAtDigit(number,

public static void Main()

    Console.WriteLine(numberOf2sinRange(22));

    Console.WriteLine(numberOf2sinRange(100));

function count2sinRangeAtDigit($number, $d)

    $powerOf10 = (int)pow(10, $d);

    $nextPowerOf10 = $powerOf10 * 10;

    $right = $number % $powerOf10;

    $roundDown = $number - $number %

    $roundup = $roundDown + $nextPowerOf10;

    $digit = ($number / $powerOf10) % 10;

        return $roundDown / 10 + $right + 1;

function numberOf2sinRange($number)

    for ($digit = 0; $digit < $len; $digit++)

        $count += count2sinRangeAtDigit($number,

print(numberOf2sinRange(22) . "\n");

print(numberOf2sinRange(100) . "\n");

    function count2sinRangeAtDigit(number , d)

        var powerOf10 = parseInt( Math.pow(10, d));

        var nextPowerOf10 = powerOf10 * 10;

        var right = number % powerOf10;

        var roundDown = number - number % nextPowerOf10;

        var roundup = roundDown + nextPowerOf10;

        var digit = parseInt(number / powerOf10) % 10;

            return roundDown / 10 + right + 1;

    function numberOf2sinRange(number)

        convert = number.toString();

        for (digit = 0; digit < len; digit++)

            count += count2sinRangeAtDigit(number, digit);

    document.write(numberOf2sinRange(22));

    document.write("<br>"+numberOf2sinRange(100));

Time Complexity:O(logN)

This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to . See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


Article Tags :