在Java中,试图打印一个整数中有多少位数字平均分为整个整数
In Java, trying to print how many digits in an integer evenly divide into the whole integer
我正在尝试打印一个整数中有多少位数字平均分为整个整数。
使用 mod 10,我得到整数的最后一位,然后除以 10 以删除最后一位,最后 mod 整数除以每个最后一位以检查每个数字是否可整除为整数。出于某种原因,我收到一个错误 (https://repl.it/CWWV/15)。
如有任何帮助,我们将不胜感激!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int singleD, n1;
int counter = 0;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
n1 = n;
while (n1 > 0){
singleD = n1%10;
n1 /= 10;
if(singleD != 0 && n%singleD == 0){
counter++;
}
}
System.out.println(counter);
counter = 0;
}
}
编辑:现在可以使用了。
我会使用String.valueOf(int)
and then convert that to a character array. Next, I would use a for-each
loop来迭代每个字符并将其解析回一个数字以测试余数1是 0
来自与原始 int
的除法,如果是这样则增加一个计数器。最后,显示计数。像,
Scanner in = new Scanner(System.in);
int counter = 0;
int t = in.nextInt();
for (char ch : String.valueOf(t).toCharArray()) {
if (ch != '0' && t % Character.digit(ch, 10) == 0) {
counter++;
}
}
System.out.println("count = " + counter);
1记得测试 0
以防止除以 0
.
我正在尝试打印一个整数中有多少位数字平均分为整个整数。
使用 mod 10,我得到整数的最后一位,然后除以 10 以删除最后一位,最后 mod 整数除以每个最后一位以检查每个数字是否可整除为整数。出于某种原因,我收到一个错误 (https://repl.it/CWWV/15)。
如有任何帮助,我们将不胜感激!
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int singleD, n1;
int counter = 0;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
int n = in.nextInt();
n1 = n;
while (n1 > 0){
singleD = n1%10;
n1 /= 10;
if(singleD != 0 && n%singleD == 0){
counter++;
}
}
System.out.println(counter);
counter = 0;
}
}
编辑:现在可以使用了。
我会使用String.valueOf(int)
and then convert that to a character array. Next, I would use a for-each
loop来迭代每个字符并将其解析回一个数字以测试余数1是 0
来自与原始 int
的除法,如果是这样则增加一个计数器。最后,显示计数。像,
Scanner in = new Scanner(System.in);
int counter = 0;
int t = in.nextInt();
for (char ch : String.valueOf(t).toCharArray()) {
if (ch != '0' && t % Character.digit(ch, 10) == 0) {
counter++;
}
}
System.out.println("count = " + counter);
1记得测试 0
以防止除以 0
.