|
1 | 1 | package com.thealgorithms.maths; |
2 | 2 |
|
3 | 3 | import java.util.ArrayList; |
4 | | -import java.util.Collections; |
5 | 4 |
|
6 | 5 | /** |
7 | 6 | * In number theory, a vampire number (or true vampire number) is a composite |
@@ -34,38 +33,32 @@ static void printVampireNumbers(int startValue, int stopValue, boolean ignorePse |
34 | 33 | } |
35 | 34 | } |
36 | 35 |
|
37 | | - static boolean isVampireNumber(int a, int b, boolean ignorePseudoVamireNumbers) { |
| 36 | + static boolean isVampireNumber(int a, int b, boolean ignorePseudoVampireNumbers) { |
38 | 37 | // Pseudo vampire numbers don't have to be of n/2 digits. E.g., 126 = 6 x 21 is such a number. |
39 | | - if (ignorePseudoVamireNumbers) { |
40 | | - if (a * 10 <= b || b * 10 <= a) { |
41 | | - return false; |
42 | | - } |
| 38 | + if (ignorePseudoVampireNumbers && String.valueOf(a).length() != String.valueOf(b).length()) { |
| 39 | + return false; |
43 | 40 | } |
44 | 41 |
|
45 | | - String mulDigits = splitIntoDigits(a * b, 0); |
46 | | - String faktorDigits = splitIntoDigits(a, b); |
| 42 | + String mulDigits = splitIntoSortedDigits(a * b); |
| 43 | + String factorDigits = splitIntoSortedDigits(a, b); |
47 | 44 |
|
48 | | - return mulDigits.equals(faktorDigits); |
| 45 | + return mulDigits.equals(factorDigits); |
49 | 46 | } |
50 | 47 |
|
51 | 48 | // Method to split a pair of numbers to digits and sort them in the ascending order. |
52 | | - static String splitIntoDigits(int num, int num2) { |
53 | | - StringBuilder res = new StringBuilder(); |
54 | | - |
| 49 | + static String splitIntoSortedDigits(int... nums) { |
| 50 | + // Collect all digits in a list. |
55 | 51 | ArrayList<Integer> digits = new ArrayList<>(); |
56 | | - while (num > 0) { |
57 | | - digits.add(num % 10); |
58 | | - num /= 10; |
59 | | - } |
60 | | - while (num2 > 0) { |
61 | | - digits.add(num2 % 10); |
62 | | - num2 /= 10; |
63 | | - } |
64 | | - Collections.sort(digits); |
65 | | - for (int i : digits) { |
66 | | - res.append(i); |
| 52 | + for (int num : nums) { |
| 53 | + while (num > 0) { |
| 54 | + digits.add(num % 10); |
| 55 | + num /= 10; |
| 56 | + } |
67 | 57 | } |
68 | 58 |
|
| 59 | + // Sort all digits and convert to String. |
| 60 | + StringBuilder res = new StringBuilder(); |
| 61 | + digits.stream().sorted().forEach(res::append); |
69 | 62 | return res.toString(); |
70 | 63 | } |
71 | 64 | } |
0 commit comments