티스토리 뷰
Problem
Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3^x.
Example 1:
Input: n = 27
Output: true
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Solution
3의 n제곱인 경우 true를 반환하는 문제입니다.
public class Solution {
public boolean isPowerOfThree(int n) {
if (n == 0) {
return false;
}
int r = 0;
while (n > 1) {
r = n % 3;
if (r != 0) {
return false;
}
n = n / 3;
}
return n == 1;
}
}
n이 1보다 클 때 3으로 계속 나눠서 n이 1인지 검사합니다.
중간중간 3으로 나눴을 때 나머지가 존재해선 안 됩니다.
Test
package io.lcalmsky.leetcode.power_of_tree;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void testAll() {
assertAll(
() -> test(27, true),
() -> test(0, false),
() -> test(9, true)
);
}
private void test(int given, boolean expected) {
// when
Solution solution = new Solution();
boolean actual = solution.isPowerOfThree(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
200. Number of Islands (0) | 2022.08.30 |
---|---|
383. Ransom Note (0) | 2022.08.29 |
342. Power of Four (0) | 2022.08.26 |
234. Palindrome Linked List (0) | 2022.08.25 |
871. Minimum Number of Refueling Stops (0) | 2022.08.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Spring Boot Tutorial
- 클린 아키텍처
- 함께 자라기
- 스프링 부트
- Java
- 스프링부트
- intellij
- gRPC
- Linux
- 헥사고날 아키텍처
- spring boot jwt
- Jackson
- Spring Data JPA
- 스프링 부트 튜토리얼
- JSON
- Spring Boot JPA
- @ManyToOne
- 스프링 데이터 jpa
- proto3
- 스프링 부트 회원 가입
- 스프링 부트 애플리케이션
- spring boot application
- Spring Boot
- r
- 함께 자라기 후기
- JPA
- QueryDSL
- 알고리즘
- spring boot app
- leetcode
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함