Number of 7 (with.Java)
This is an article about the “Number of 7 (with.Java)” problem.
As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.
Let’s look at the problem first.
problem
My favorite lucky number is 7.
When an integer array array is given as a parameter, complete the solution function to return the total number of 7s.
Restrictions
- 1 ≤ length of array ≤ 100
- 0 ≤ elements of array ≤ 100,000
Input/Output Example
array | result |
---|---|
[7, 77, 17] | 4 |
[10, 29] | 0 |
My solution to the problem
class Solution {
public int solution(int[] array) {
int answer = 0;
for(int i = 0; i < array.length; i++){
String str = String.valueOf(array[i]);
char[] chArr = str.toCharArray();
for(char ch : chArr){
if(ch == '7'){
answer += 1;
}
}
}
return answer;
}
}
Solution explanation
public int solution(int[] array)
: The solution method is a method that takes an int array as input and returns the number of 7.int answer = 0;
: Declare the answer variable and initialize it to 0. This variable is a variable that will store the number of 7.for(int i = 0; i < array.length; i++)
: This is a loop that repeats the length of the array. It is used to check all the elements in an array one by one.String str = String.valueOf(array[i]);
: Converts the elements of the array to a string. The reason for converting an element of an array to a string is to check if that number is 7.char[] chArr = str.toCharArray();
: Converts a string to a character array. The reason for this conversion is to loop through the strings one by one and check whether it is 7.for(char ch : chArr)
: It is a loop statement that checks all elements of a character array one by one.if(ch == '7')
: Checks whether the character currently being checked is 7.answer += 1;
: If the character is 7, 1 is added to the answer variable. That is, increase the number of 7 by 1.return answer;
: After the loop ends, returns the answer variable that stores the number of 7.
The code implemented in this way performs the function of counting the number of 7s in the given array.