[C++] 백준 1740번 거듭제곱

xyzw·2025년 3월 14일
0

algorithm

목록 보기
55/61

https://www.acmicpc.net/problem/1740

풀이

n을 이진수로 표현한 후, 3의 거듭제곱을 더해주면 된다.

ex. 1) n = 4
n -> 100
ans = 3^2

ex. 2) n = 9
n -> 1001
ans = 3^3 + 3^0

코드

#include <iostream>
using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    
    long long n, ans=0;
    cin >> n;
    
    long long power=1;
    while(n) {
        if(n & 1) ans += power;
        power *= 3;
        n >>= 1;
    }
    
    cout << ans;
    return 0;
}

0개의 댓글

Powered by GraphCDN, the GraphQL CDN