简体   繁体   English

在Java中,尝试打印整数中的多少位数均匀地划分为整数

[英]In Java, trying to print how many digits in an integer evenly divide into the whole integer

I'm trying to print how many digits in an integer evenly divide into the whole integer. 我正在尝试打印整数中的多少位数均匀地分成整个整数。

Using mod 10, I get the last digit of the integer, then do division by 10 to remove the last digit, and finally mod integer by each last digit to check if each digit is divisible into the whole integer. 使用mod 10,我得到整数的最后一位,然后除以10以除去最后一位,最后通过mod mod by每一位最后一位来检查每个数字是否可整整为整数。 For some reason I'm getting an error ( https://repl.it/CWWV/15 ). 由于某种原因,我遇到了错误( https://repl.it/CWWV/15 )。

Any help would be greatly appreciated! 任何帮助将不胜感激!

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;
    }

}

Edit: it now works. 编辑:现在可以。

I would use String.valueOf(int) and then convert that to a character array. 我将使用String.valueOf(int) ,然后将其转换为字符数组。 Next, I would use a for-each loop to iterate each character and parse it back to a digit for testing if the remainder 1 is 0 from division with the original int and if so increment a counter. 接下来,我将使用for-each循环迭代每个字符,并将其解析回一个数字,以测试从原始int除以余数1是否为0 ,如果是,则增加一个计数器。 Finally, display the count. 最后,显示计数。 Something like, 就像是,

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 Remembering to test for 0 to prevent division by 0 . 1 记住测试0以防止被0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM