-

[프로그래머스] 레벨 2 - 124 나라의 숫자 본문

1-4. 프로그래머스

[프로그래머스] 레벨 2 - 124 나라의 숫자

asdklfjlasdlfkj 2020. 2. 2. 23:32

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

 

코딩테스트 연습 - 124 나라의 숫자 | 프로그래머스

124 나라가 있습니다. 124 나라에서는 10진법이 아닌 다음과 같은 자신들만의 규칙으로 수를 표현합니다. 124 나라에는 자연수만 존재합니다. 124 나라에는 모든 수를 표현할 때 1, 2, 4만 사용합니다. 예를 들어서 124 나라에서 사용하는 숫자는 다음과 같이 변환됩니다. 10진법 124 나라 10진법 124 나라 1 1 6 14 2 2 7 21 3 4 8 22 4 11 9 24 5 12 10 41 자연수 n이 매개변수로 주어질 때, n을 124

programmers.co.kr

124 나라의 숫자 문제다.

단순 수학 계산 문제로 정수형 변수의 몫과 나머지를 이용해 푸는 문제였다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <vector>
#include <sstream>
using namespace std;
 
string solution(int n) {
    string answer = "";
    while(n > 0){
        ostringstream ostr;
        if((n % 3!= 0){
            ostr << (n % 3);
            answer = ostr.str() + answer;
            n /= 3;
        }
        else {
            answer = "4" + answer;
            n = (n/3)-1;
        }
    }
    return answer;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

 

위 풀이는 정답인데, 10번째 줄에 if 문 내부에 (n % 3)에서 괄호를 빼면 오답처리가 되는 케이스가 존재한다. 분명히 연산자 우선순위는 %가 != 연산자보다 더 우선인데도 말이다. 이유를 참 모르겠네. 아무튼 if문 내부에는 앞으로 꼭 좌우변을 구분해주어 코딩하자.

 

다른 답 보니까 string 라이브러리에 있는 to_string을 많이 쓰는거 같은데 그냥 이게 익숙하니까 이 방법을 썼다. 

문자열 -> 정수, 정수 -> 문자열 방법은 아래 참조.

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
#include <sstream>
//1. string to int
 
    string s = "12345";
 
    stringstream geek(s);
 
    int x;
 
    geek >> x;
 
    cout << "string to int: " << x << '\n';
 
 
 
    //2. int to string
 
    int y = 12345;
 
    ostringstream ostr;
 
    ostr << y;
 
    string s_2 = ostr.str();
 
    cout << "int to string: " << s_2 << '\n';
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs

그리고 string 라이브러리에 있는 insert 함수로 손쉽게 string에 다른 문자열을 추가할 수 있다.

아래와 같다.

문자열을 추가할 원본 문자열의 인덱스, 넣을 문자열, (넣을 문자열의 시작 인덱스와 갯수).


Comments