Armstrong Number in Java (#12637)

This commit is contained in:
Kai Yuan 2022-08-25 03:40:26 +02:00 committed by GitHub
parent 876d78b188
commit 18d1cb40dc
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,44 @@
package com.baeldung.armstrong;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ArmstrongNumberUtil {
public static boolean isArmstrong(int n) {
if (n < 0) {
return false;
}
List<Integer> digitsList = digitsInList(n);
int len = digitsList.size();
int sum = digitsList.stream()
.mapToInt(d -> (int) Math.pow(d, len))
.sum();
// alternatively, we can use the reduce() method:
// int sum = digits.stream()
// .reduce(0, (subtotal, digit) -> subtotal + (int) Math.pow(digit, len));
return n == sum;
}
private static List<Integer> digitsInList(int n) {
List<Integer> list = new ArrayList<>();
while (n > 0) {
list.add(n % 10);
n = n / 10;
}
return list;
}
public static List<Integer> getA005188Sequence(int limit) {
if (limit < 0) {
throw new IllegalArgumentException("The limit cannot be a negative number.");
}
return IntStream.range(0, limit)
.boxed()
.filter(ArmstrongNumberUtil::isArmstrong)
.collect(Collectors.toList());
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.armstrong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
class ArmstrongNumberUtilUnitTest {
// @formatter:off
private static final Map<Integer, Boolean> ARMSTRONG_MAP = ImmutableMap.of(
0, true,
1, true,
2, true,
153, true,
370, true,
407, true,
42, false,
777, false,
12345, false);
// @formatter:on
private static final List<Integer> A005188_SEQ_1K = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407);
private static final List<Integer> A005188_SEQ_10K = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474);
@Test
void givenIntegers_whenCheckArmstrong_shouldReturnExpectedResult() {
ARMSTRONG_MAP.forEach((number, result) -> assertEquals(result, ArmstrongNumberUtil.isArmstrong(number)));
}
@Test
void givenALimit_whenFindArmstrong_shouldReturnExpectedResult() {
assertEquals(A005188_SEQ_1K, ArmstrongNumberUtil.getA005188Sequence(1000));
assertEquals(A005188_SEQ_10K, ArmstrongNumberUtil.getA005188Sequence(10000));
}
}