devGYU World
[Exercism Dart] Armstrong Numbers 솔루션 본문

본 예제는 입력받은 수가 암스트롱 수인가 여부를 판별한다.
암스트롱 수란 기재된 것과 같이 각 자릿수 값의 자릿수 개수만큼의 거듭제곱들의 합이 원래 수와 같은지 말이다.
따라서 입력받은 수의 자릿수와 갯수를 구해서 각 값들의 합이 원래 수와 같은지를 판별해야 한다.
import 'dart:math';
class ArmstrongNumbers {
bool isArmstrongNumber(int? number) {
int armNum = 0;
//입력받은 수를 String으로 변환하여 Length를 구하면 자릿수를 알 수 있다.
//String으로 변환된 수를 split한 뒤 다시 int 타입으로 변환하여 제곱값을 구한다.
//모든 과정을 fold() 함수를 통해 누적 값을 구한다.
number.toString().split('').fold(armNum, (previousValue, element) {
return pow(int.parse(element), number.toString().length);
});
//누적값이 입력값과 같다면 암스트롱 수이지만 그렇지 않다면 암스트롱 수가 아니다.
return armNum == number ? true : false;
}
}
참고
Armstrong Numbers in Dart on Exercism
Can you solve Armstrong Numbers in Dart? Improve your Dart skills with support from our world-class team of mentors.
GitHub - gyu0710/dart: Exercism Dart Solutions
Exercism Dart Solutions. Contribute to gyu0710/dart development by creating an account on GitHub.
github.com
'etc > exercise' 카테고리의 다른 글
[ Exercism Dart] Scrabble Score 솔루션 (0) | 2022.03.18 |
---|---|
[ Exercism Dart] Difference Of Squares 솔루션 (0) | 2022.03.18 |
[Exercism Dart] Leap 솔루션 (0) | 2022.03.18 |
[Exercism Dart] Two Fer 솔루션 (0) | 2022.03.18 |
[Exercism Dart] Hello World 솔루션 (0) | 2022.03.18 |
Comments