TDD로 알고리즘 풀이 후 리팩토링
리팩토링해서 함수만들고 하면 성능이 좀 떨어짐
테스트코드
package algorithm_sites.leetcode;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
public class LeetCode_1742_MaximumNumberOfBallsInABoxTest {
private LeetCode_1742_MaximumNumberOfBallsInABox test = new LeetCode_1742_MaximumNumberOfBallsInABox();
@Test
public void countBallsTest() {
Assertions.assertThat(test.countBalls(1, 10)).isEqualTo(2);
Assertions.assertThat(test.countBalls(5, 15)).isEqualTo(2);
Assertions.assertThat(test.countBalls(19, 28)).isEqualTo(2);
}
@Test
public void digitSumTest() {
Assertions.assertThat(test.digitSum(12)).isEqualTo(3);
Assertions.assertThat(test.digitSum(312)).isEqualTo(6);
Assertions.assertThat(test.digitSum(4572)).isEqualTo(18);
Assertions.assertThat(test.digitSum(9380)).isEqualTo(20);
Assertions.assertThat(test.digitSum(0)).isEqualTo(0);
Assertions.assertThat(test.digitSum(1)).isEqualTo(1);
Assertions.assertThat(test.digitSum(990)).isEqualTo(18);
}
}
풀이코드
package algorithm_sites.leetcode;
/**
* Written by Gin (thesockerr@gmail.com) on 2021/12/11.
*/
public class LeetCode_1742_MaximumNumberOfBallsInABox {
int[] boxes = new int[10 * 100000];
// Process
// 1. Input low high limits
// 2. Iterate low to high (num)
// 2.1. Get digitSum of num
// 2.2. Put digitSum in boxNumber
// 3. Get maxBoxNumber
// 4. Return
public int countBalls(int lowLimit, int highLimit) {
// 2.
fillTheBoxes(lowLimit, highLimit);
// 3. / 4.
return findMaxNumberOfMaxCountBox();
}
private void fillTheBoxes(int lowLimit, int highLimit) {
for (int i = lowLimit; i <= highLimit; ++i) {
++boxes[digitSum(i)];
}
}
private int findMaxNumberOfMaxCountBox() {
int max = 0;
for (int i = 0; i < boxes.length; ++i) {
if (max < boxes[i]) {
max = boxes[i];
}
}
return max;
}
protected int digitSum(int number) {
int sum = 0;
while (number > 0) {
sum += (number % 10);
number /= 10;
}
return sum;
}
}
문제 영어 독해가 빡쎘음..
'Programming' 카테고리의 다른 글
Spring Security 5 OAuth 정리 (클라에서 서버까지) (0) | 2021.12.17 |
---|---|
Oracle to MySQL 변환 시 고려사항 (RDBMS) (0) | 2021.12.15 |
[LeetCode] 2085. Count common words with one occurrence (코딩테스트, 테스트케이스 포함, 릿코드, tech interview) (0) | 2021.12.04 |
Gradle 의존 키워드의 차이점 (compile vs implementation + api, Gradle dependency configurations diff) (0) | 2021.11.28 |
RPC, 근데 이제 Json을 곁들인.. (Json-RPC) (0) | 2021.11.17 |