简体   繁体   中英

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. For some reason I'm getting an error ( 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. 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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