From c22990ba71836da44d6d55c94079d8693940faf5 Mon Sep 17 00:00:00 2001 From: noah Date: Thu, 21 May 2020 09:29:20 +0900 Subject: [PATCH] Solve harshad number problem Training JS programming by solving harshad-number-problem. See also: -https://programmers.co.kr/learn/courses/30/lessons/12947 --- js-training/20200520/Harshad.test.js | 28 ++++++++++++++++++++++++++++ js-training/20200520/README.md | 8 ++++++++ 2 files changed, 36 insertions(+) create mode 100644 js-training/20200520/Harshad.test.js create mode 100644 js-training/20200520/README.md diff --git a/js-training/20200520/Harshad.test.js b/js-training/20200520/Harshad.test.js new file mode 100644 index 0000000..13843cb --- /dev/null +++ b/js-training/20200520/Harshad.test.js @@ -0,0 +1,28 @@ +function solution1(x) { + const numbers = [...('' + x)].reduce((acc ,cur) => + acc + parseInt(cur, 10), 0) + return (x % numbers === 0); +} + +function solution2(x) { + const sum = (acc, next) => { + if (next.length === 0) { + return acc; + } + + const result = +next.slice(next.length - 1) + acc; + + return sum(result, next.slice(0, next.length - 1)) + } + + return (x % sum(0, x.toString()) === 0); +} + +test('sample', () => { + [solution1, solution2].forEach((solution) => { + expect(solution(10)).toBe(true); + expect(solution(12)).toBe(true); + expect(solution(11)).toBe(false); + expect(solution(13)).toBe(false); + }); +}); diff --git a/js-training/20200520/README.md b/js-training/20200520/README.md new file mode 100644 index 0000000..bb87a97 --- /dev/null +++ b/js-training/20200520/README.md @@ -0,0 +1,8 @@ +# 하샤드 수 문제 + +양의 정수 x가 하샤드 수이려면 x의 자릿수의 합으로 x가 나누어져야 합니다. +예를 들어 18의 자릿수 합은 1+8=9이고, 18은 9로 나누어 떨어지므로 18은 하샤드 수입니다. +자연수 x를 입력받아 x가 하샤드 수인지 아닌지 검사하는 함수, solution을 완성해주세요. + +제한 조건 +x는 1 이상, 10000 이하인 정수입니다.