最近我尝试参加HackerRank挑战,涉及计算数字的空洞并将它们相加,在一番研究后,我最终将其转化为字符数组,并选择三个值进行递增,并将它们相加得到总和,如下所示:
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;
}
}
但是字符数组总是返回一个普通整数!我无法尝试模数方法,因为0被使用(有一个洞),以及一堆对String.valueOf(num).toCharArray()的变体,如("" + num).toCharArray()和Integer.toString(number).toCharArray(),但它仍然输出输入的数字而不是想要的字符数组。当然,由于空数组,该方法的其余部分都会输出0。
我有点新手,但这真让人沮丧。我感觉这是一个微小的细节,我没有看到或者不知道,而不是我的逻辑问题。请帮帮我好吗?
Arrays.toString
) - GBlodgett