간만에 문제풀이
- 테스트코드
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
public class LeetCode_0202_HappyNumberTest {
@Test
public void isHappyTest() {
LeetCode_0202_HappyNumber test = new LeetCode_0202_HappyNumber();
assertThat(test.isHappy(19)).isEqualTo(true);
assertThat(test.isHappy(2)).isEqualTo(false);
}
}
- 풀이코드
import java.util.HashSet;
import java.util.Set;
public class LeetCode_0202_HappyNumber {
boolean isHappy(int n) {
int sumOfSquaresOfDigits = n;
Set<Integer> set = new HashSet<>();
while (sumOfSquaresOfDigits != 1 && !set.contains(sumOfSquaresOfDigits)) {
set.add(sumOfSquaresOfDigits);
sumOfSquaresOfDigits = getSumOfSquaresOfDigits(sumOfSquaresOfDigits);
}
return (sumOfSquaresOfDigits == 1);
}
private int getSumOfSquaresOfDigits(int number) {
int sum = 0;
while (number > 0) {
sum += Math.pow((number % 10), 2);
number /= 10;
}
return sum;
}
}
2021.12.28 - [Programming] - Effective Java 2/E, 이펙티브 자바 책 핵심요약
'Algorithm > Leet Code' 카테고리의 다른 글
[LeetCode] 1. TwoSum + 테스트케이스 (2) | 2022.04.22 |
---|---|
[LeetCode] 130. Surrounded Regions (BFS, DFS, TDD, 코테, 릿코드, tech interview) (0) | 2022.01.03 |
[LeetCode] 94. Maximum Number of Balls in a Box (TDD, 코테, 릿코드, tech interview) (0) | 2021.12.19 |
[LeetCode] 771. Jewels and Stones(코딩테스트, 릿코드, tech interview) (0) | 2021.09.22 |
[LeetCode] 7. Reverse Integer (코딩테스트, 릿코드, tech interview) (0) | 2021.08.26 |