Lucky Seven Problem in Java
In this Java tutorial, we will learn how to solve lucky seven problem in Java. We will also take a look at the code snippet with the output.
Problem Statement – Solve Lucky Seven problem in Java
In the problem, we are provided with a number. We have to find the total count of digit 7 in the number.
Example: The number is 7487 so, the total count of digit 7 in the number is 2.
Integer to String Conversion in Java
Syntax :- Integer.toString( number ) ;
from this expression number will be converted into String .
String to Character Array Conversion in Java
Syntax:- String.toCharArray () ;
from this expression String will be converted to character array.
Also, learn,
- Guess The Number Game Using Java with Source Code
- Program to find all distinct solutions to N-Queens problem in Java
Algorithm to solve lucky seven problem in Java
- Scan a number n .
- Convert the number to String using Integer.toString() .
- Convert String to character array using String.toCharArray() .
- Now, check for each character in CharArray formed if it is ‘7’ increment count.
- Finally, print the count.
Java Code to count the total occurrence of digit 7 in a given number
import java.util.Scanner; public class Codespeedy { public static void count ( int n ) { String str = Integer.toString(n); char [] s = str.toCharArray(); int count=0; for( int i=0 ; i<s.length ; i++ ) { if ( s[i]=='7') { count++; } } System.out.println(count); } public static void main ( String[] args ) { Scanner scan = new Scanner ( System.in); int n; n = scan.nextInt(); count(n); } }
INPUT
7657347
OUTPUT
3
In the given number 7 occurs 3 times so, the output is 3.
Also learn,
Leave a Reply