class Solution {
fascinating
returns a boolean, true/false to the question, "is it fascinating?"
boolean fascinating(String q) {
int A[] = {0, 0, 0, 0, 0, 0,
0, 0, 0, 0}; // to store count of every digit from '0' to '9'
Here you just initialize A as an array of zeroes, effectively (but not technically) 'empty'.
int i, flag = 0;
char ch;
Here you initialize i
and flag
at 0 and declare ch
.
for (i = 0; i < q.length(); i++) {
ch = q.charAt(i);
A[ch - 48]++;
}
Here you have a for
loop that goes through each character in q
.
For example, let q = 192384576. This is not N, but rather N concatenated with (Nx2) concatenated with (Nx3).
So the for
loop first sets ch = q.charAt(0)
. This is the first character, 1. Then it increments (adds one to) a certain index in A
.
This index, much credit and thanks to Andreas for explaining this, is the difference of the Numeric ASCII value for ch
and 48, which is the Numeric ASCII value for 0.
In Numeric ASCII:
0 = 48
1 = 49
2 = 50
3 = 51
and the rest.
Therefore, ch-48
will give the index in A
that should represent ch
. For example, when ch
is 1, ASCII value of ch
is 49
and 49-48 = 1
. Therefore, it goes to A[1]
and increments it.
Remember, arrays go [0,1,2,3, etc.]
So it goes to [0, 0, 0, etc]
and adds one to the second 0 -- A[1]
, thus making A = [0,1,0,etc]
.
It continues through each digit in q
, and thus fills the array A
.
for (i = 1; i < 10; i++) {
// checking if every digit from '1' to '9' are present exactly once
// or not
if (A[i] != 1) {
flag = 1; // flag is set to 1 if frequency is not 1
break;
}
}
Here, it iterates through A
, set to length 10
because we are checking 0-9, and checks at each index if the value in that index is equal to 1. Hence,
if (A[i]!=1){}
The array should look like [1,1,1,1,etc].
If any of these indices is found not to be 1, it sets flag = 1
and immediately will break
or exit the for
loop.
if (flag == 1)
return false;
else
return true;
}
}
This final if-else
statement checks whether flag
is equal to 1
. Remember, we only set it equal to 1 if the array is not uniformly filled with 1's, meaning the String q
does not contain exactly one of each digit 0-9.
If flag
is 1, return false
, meaning it is not fascinating. Otherwise, it is fascinating. Thus, when fascinating, return true
.