Lucky Sevens. Given a whole number, compute and display how many digits in the number are 7s. For example, the number of 7s in 3482 is 0, while the number of 7s in 372771 is 3. Note: whole numbers are non-negative integers starting at zero {0, 1, 2, 3, 4, …}

Respuesta :

tanoli

Answer:

Code is in both c++ and java

Explanation:

C++ Code

#include<iostream>  

#include <sstream>  // for string streams  

#include <string>  // for string  

using namespace std;  

int main()  

{  

   int num;  

   cout<<"Enter Non-Negative number :";

  cin>> num;

   // declaring output string stream  

   ostringstream str1;  

   // Sending a number as a stream into output  

   // string  

   str1 << num;  

   // the str() coverts number into string  

   string geek = str1.str();  

   int count =0;

  for (int i = 0; i < geek.size(); i++){

    if(geek[i]=='7'){

     count++;  

 }

}

   // Displaying the string  

   cout << "the number of 7s in "<<num<< "is"<<count;

 

   return 0;  

}

Java Code

import java.util.Scanner;

public class LuckySeven{

   public static void main(String[] args){

       Scanner scanner = new Scanner(System.in);

       System.out.print("Enter Number :");

       int number = scanner.nextInt();

       String numberString = number+"";

       int count =numberString.length()- numberString.replaceAll("7","").length();

       System.out.println("Number of 7's in "+numberString+" are "+count);

   }

}

Code Explanation

First we need to take integer number as input from user.

As we need to iterate through all of the digits in number, that's why we need to convert integer to string as string is an array of character so we will iterate through number array and match the total count of 7 on every index.

At the end we will display the total count of 7 in number.

Sample Output

Case 1

Enter Non-Negative number :3482

the number of 7s in 3482 is 0

Case 2

Enter Non-Negative number :372771

the number of 7s in 372771 is 3