관리 메뉴

Partially Committed

[μ›”κ°„ μ½”λ“œ μ±Œλ¦°μ§€ μ‹œμ¦Œ1] 3진법 뒀집기 λ³Έλ¬Έ

πŸ”₯ Algorithm || λ¬Έμ œν’€μ΄/PS

[μ›”κ°„ μ½”λ“œ μ±Œλ¦°μ§€ μ‹œμ¦Œ1] 3진법 뒀집기

WonderJay 2022. 7. 4. 18:15
728x90
λ°˜μ‘ν˜•
SMALL

https://programmers.co.kr/learn/courses/30/lessons/68935

 

μ½”λ”©ν…ŒμŠ€νŠΈ μ—°μŠ΅ - 3진법 뒀집기

μžμ—°μˆ˜ n이 λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§‘λ‹ˆλ‹€. n을 3진법 μƒμ—μ„œ μ•žλ’€λ‘œ 뒀집은 ν›„, 이λ₯Ό λ‹€μ‹œ 10μ§„λ²•μœΌλ‘œ ν‘œν˜„ν•œ 수λ₯Ό return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό μ™„μ„±ν•΄μ£Όμ„Έμš”. μ œν•œμ‚¬ν•­ n은 1 이상 100,000,000 μ΄ν•˜μΈ μžμ—°μˆ˜

programmers.co.kr

μžμ—°μˆ˜ n 을 3진법 으둜 λ³€ν™˜ν•œ λ’€, μ•žλ’€λ₯Ό 뒀집고 λ‹€μ‹œ 10μ§„λ²•μœΌλ‘œ λ°”κΎΈμ–΄ λ¦¬ν„΄ν•΄μ•Όν•œλ‹€.

 

vector<int> third λ₯Ό μ •μ˜ν•˜κ³ , n 이 0보닀 클 λ•ŒκΉŒμ§€ n 을 3으둜 λ‚˜λˆˆ λͺ«μ„ third 에 push_back ν•˜κ³  n /= 3 으둜 μ—…λ°μ΄νŠΈ ν•˜λŠ” 것을 λ°˜λ³΅ν•˜λ©΄ third μ—λŠ” 3μ§„λ²•μœΌλ‘œ λ³€ν™˜ν•œ λ’€ 뒀집은 μˆ˜κ°€ μ €μž₯λœλ‹€.

이제 third λ₯Ό 거꾸둜 μˆœνšŒν•˜λ©° 10μ§„λ²•μœΌλ‘œ λ³€ν™˜ν•˜κΈ° μœ„ν•΄ int i = 1 을 μ •μ˜ν•˜κ³ ,

LSB λΆ€ν„° i λ₯Ό κ³±ν•΄μ„œ answer 에 λ”ν•œλ‹€. 그리고 i *= 3 으둜 μ—…λ°μ΄νŠΈν•˜λŠ” 것을 λ°˜λ³΅ν•˜λ©΄ λœλ‹€.

 

[C++]

#include <string>
#include <vector>

using namespace std;

int solution(int n) {
    int answer = 0;

    vector<int> third;
    while (n > 0)
    {
        third.push_back(n%3);
        n /= 3;
    }

    int i = 1;
    for (vector<int>::reverse_iterator iter = third.rbegin(); 
        iter != third.rend(); iter++)
    {
        answer += (i * (*iter));
        i *= 3;
    }

    return answer;
}

 

 

728x90
λ°˜μ‘ν˜•
LIST
Comments