Problem
An integer is a divisor of an integer if the remainder of .
Given an integer, for each digit that makes up the integer determine whether it is a divisor. Count the number of divisors occurring within the integer.
Note: Each digit is considered to be unique, so each occurrence of the same digit should be counted (e.g. for , is a divisor of each time it occurs so the answer is ).
Function Description
Complete the findDigits function in the editor below. It should return an integer representing the number of digits of that are divisors of .
findDigits has the following parameter(s):
- n: an integer to analyze
Input Format
The first line is an integer, , indicating the number of test cases.
The subsequent lines each contain an integer, .
Constraints
Output Format
For every test case, count the number of digits in that are divisors of . Print each answer on a new line.
Sample Input
2
12
1012
Sample Output
2
3
Explanation
The number is broken into two digits, and . When is divided by either of those two digits, the remainder is so they are both divisors.
The number is broken into four digits, , , , and . is evenly divisible by its digits , , and , but it is not divisible by as division by zero is undefined.
How I solved the problem
# 주어진 int를 String으로 바꿔서 총 자리수를 구하는게 처음.
# for문을 돌면서 주어진 int를 각 자리수로 나누어야함 (이 때, 0으로는 나눌 수 없기 때문에 0일 때는 continue를 써줌!!!)
# 나누었을 때 나머지가 0인 경우에만 개수에 +1을 해주는 식으로 해야함.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { // Complete the findDigits function below. static int findDigits(int n) { String nStr = n + ""; int nStrLength = nStr.length(); int result = 0; for (int i = 0; i < nStrLength; i++) { int digit = Integer.parseInt(nStr.charAt(i) + ""); if (digit == 0) { continue; } if (n % digit == 0) { result++; } } return result; } private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); int t = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int tItr = 0; tItr < t; tItr++) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int result = findDigits(n); bufferedWriter.write(String.valueOf(result)); bufferedWriter.newLine(); } bufferedWriter.close(); scanner.close(); } } | cs |
[출처 : https://www.hackerrank.com ]
'1 Day 1 Algorithms' 카테고리의 다른 글
[2019.03.15] Extra Long Factorials (0) | 2019.03.15 |
---|---|
[2019.03.13] Jumping on the Clouds: Revisited (0) | 2019.03.13 |
[2019.03.12] Sequence Equation (0) | 2019.03.12 |
[2019.03.11] Circular Array Rotation (0) | 2019.03.11 |
[2019.03.07] Save the Prisoner! (0) | 2019.03.07 |
댓글