Notice
Recent Posts
Recent Comments
-
[프로그래머스] 레벨 2 - 124 나라의 숫자 본문
https://programmers.co.kr/learn/courses/30/lessons/12899
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);
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;
cout << "int to string: " << s_2 << '\n';
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
그리고 string 라이브러리에 있는 insert 함수로 손쉽게 string에 다른 문자열을 추가할 수 있다.
아래와 같다.
문자열을 추가할 원본 문자열의 인덱스, 넣을 문자열, (넣을 문자열의 시작 인덱스와 갯수).
'1-4. 프로그래머스' 카테고리의 다른 글
[프로그래머스] 레벨 2 - 탑 (0) | 2020.02.03 |
---|---|
[프로그래머스] 레벨 2 - 카카오프렌즈 컬러링북 (2017 카카오코드 예선) (0) | 2020.02.03 |
[프로그래머스] 레벨 3 - N으로 표현 (0) | 2020.01.31 |
[프로그래머스] 레벨 2 - 쇠막대기 (0) | 2020.01.31 |
[프로그래머스] 레벨 2 - 멀쩡한 사각형 (0) | 2020.01.31 |
Comments