Skip to content

Commit d814c6f

Browse files
committed
Refactor other methods in VampireNumber
- Fix a bug in check for pseudo vampire number - Make method that split into digits accept vararg and slightly simplify it
1 parent 65cad79 commit d814c6f

File tree

1 file changed

+16
-23
lines changed

1 file changed

+16
-23
lines changed

src/main/java/com/thealgorithms/maths/VampireNumber.java

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package com.thealgorithms.maths;
22

33
import java.util.ArrayList;
4-
import java.util.Collections;
54

65
/**
76
* 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
3433
}
3534
}
3635

37-
static boolean isVampireNumber(int a, int b, boolean ignorePseudoVamireNumbers) {
36+
static boolean isVampireNumber(int a, int b, boolean ignorePseudoVampireNumbers) {
3837
// 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;
4340
}
4441

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);
4744

48-
return mulDigits.equals(faktorDigits);
45+
return mulDigits.equals(factorDigits);
4946
}
5047

5148
// 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.
5551
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+
}
6757
}
6858

59+
// Sort all digits and convert to String.
60+
StringBuilder res = new StringBuilder();
61+
digits.stream().sorted().forEach(res::append);
6962
return res.toString();
7063
}
7164
}

0 commit comments

Comments
 (0)