So I recently attempted to do the HackerRank challenge that involved counting a number's holes and adding them up, and after a bit of research, I ended up making it into a char array and choosing three values to increment and add up to the sum as shown below:
public static int countHoles(int num) {
//create integers that count how many a number with no, one or two holes shows up
Integer noHoles = 0;
Integer oneHole = 0;
Integer twoHoles = 0;
Integer sum = 0;
Integer length = 0;
//turn the inputted number into a char array
char [] digits = String.valueOf(num).toCharArray();
System.out.println(digits);
length = digits.length;
//These nested loops incremement the numbers initialized above as the first for-each loop goes through each index value of the array
for (int i = 0; i < digits.length; i++){
if (digits[i]== 1 || digits[i]==2 || digits[i]==3 || digits[i]==5 || digits[i]==7){
noHoles++;
} else if (digits[i]==4 || digits[i]==6 || digits[i]==9 || digits[i]==0){
oneHole+= 1;
} else if (digits[i]==8){
twoHoles+= 2;
}
}
//add up the incremented integers. twoHoles is doubled as each unit counts as two holes and noHoles is 0 regardless of its values
sum = oneHole + twoHoles;
return sum;
}
}
but the char array always return as a normal integer! I can't try the modulus approach since 0 is used (has one hole in it), and a bunch of variants on String.valueOf(num).toCharArray() such as ("" + num).toCharArray() and Integer.toString(number).toCharArray(), but it stills outputs the inputted number instead of the wanted char array. Of course, the rest of the method spits out 0 because of the empty array too.
I'm a bit of a newbie, but damn is this frustrating. I feel like it's a micro-detail I haven't seen or don't know instead of my logic. Any help please?
You're comparing a char
to an int
with the incorrect int
values (for example, '1' != 1
). It would safer to compare char
to char
:
if (digits[i] == '1' || digits[i] == '2' || digits[i] == '3' || digits[i] == '5' || digits[i] == '7') {
noHoles++;
} else if (digits[i] == '4' || digits[i] == '6' || digits[i] == '9' || digits[i] == '0') {
oneHole += 1;
} else if (digits[i] == '8') {
twoHoles += 2;
}
You also don't need the noHoles
variable, as it goes unused after it's incremented. If you remove noHoles
, you can also remove the first if-statement where you check if the number is 1
, 2
, etc.
Also to print your char[]
, use Arrays#toString
:
System.out.println(Arrays.toString(digits));