반응형
https://leetcode.com/problems/power-of-four/description/
Power of Four - LeetCode
Power of Four - Given an integer n, return true if it is a power of four. Otherwise, return false. An integer n is a power of four, if there exists an integer x such that n == 4x. Example 1: Input: n = 16 Output: true Example 2: Input: n = 5 Output: fal
leetcode.com
구현 문제였습니다.
📕 풀이방법
📔 풀이과정
1. 자료형이 int를 넘어갈 수 있으므로 1을 LL로 casting해주며 매 loop마다 i를 2씩 증가해 4씩 곱하도록 for loop를 구현해줍니다.
2. 1에서 i만큼 bit를 왼쪽으로 옮겼을 때 n과 같다면 true를 아니라면 false를 반환합니다.
* 4^x로는 0이하의 수를 만들 수 없습니다.
📕 Code
📔 C++
class Solution {
public:
bool isPowerOfFour(int n) {
for(int i = 0; (1LL << i) <= n; i += 2) {
if((1 << i) == n) return true;
}
return false;
}
};
*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.
'Algorithm > Implementation' 카테고리의 다른 글
(C++) - LeetCode (easy) 409. Longest Palindrome (0) | 2023.03.09 |
---|---|
(C++) - LeetCode (easy) 405. Convert a Number to Hexadecimal (0) | 2023.03.07 |
(C++) - LeetCode (easy) 338. Counting Bits (0) | 2023.02.14 |
(C++) - LeetCode (easy) 326. Power of Three (0) | 2023.02.13 |
(C++) - LeetCode (easy) 292. Nim Game (0) | 2023.02.08 |