알고리즘 코드카타

변수 타입 변경이 너무 헷갈려~~
파이썬에서는 알잘딱깔센해줬던거같은데..
하하 그래서 한 번 정리하고 넘어가야겠다.
1. int to char
int before = 3;
char after = before + '0';
// 또는 char after = before + 48;
2. char to int
char before = '3';
int after = before - '0';
// 또는 int after = before - 48;
3. int to string
#include <string>
int before = 100;
string s = to_string(before);
4. string to int
#include <string>
string s = "100";
int i = stoi(s);
만약 정수와 문자가 섞여 있다면 문자 이전까지만 변환 !
5. string to (숫자)
| int로 변환 | stoi(); |
| long으로 변환 | stol(); |
| double로 변환 | stod(); |
| float로 변환 | stof(); |
프로그래머스 - 푸드 파이트 대회
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(vector<int> food) {
string answer = "";
string temp="";
for(int i=1;i<food.size();i++){
int n=food[i]/2;
for(int j=0;j<n;j++){
temp.push_back(i+'0');
}
}
answer=temp+"0";
reverse(temp.begin(),temp.end());
answer+=temp;
return answer;
}
2명이 나눠 가져야하니까 2로 나눠주고 그 숫자만큼 index(i)를 문자로 변경하여 push_back 해준다.
그리고 중앙에는 물(0)이 와야하니 + 연산을 통해 문자열을 합쳐주고 값을 reverse하여 다시 합쳐준다.
참고
https://8156217.tistory.com/28#google_vignette
[c++] ( int to char / char to int / int to string / string to int ) 정리 및 예제 (to_string , stoi , '0' , 48)
오늘은 c++에서 변수의 타입을 변경해야 할 때 사용하는 함수 및 방법을 정리해봤다. Ps에서 정말 많이 사용 되기 때문에 반드시 알고 있어야 한다. 1) int -> char 변환 ◎ '0' or 48을 더해준다. int befor
8156217.tistory.com
https://developer-cat.tistory.com/20#google_vignette
[C++] - string → int 로 형변환하기
1. stoi() 메소드 이용하기 (string -> 모든 숫자형 가능) stoi() 메소드는 간단하게 string을 int로 바꿀 수 있는 함수이다. (string to int 에서 앞 문자를 따와서 stoi라고 부른다.) stoi(string변수명) 이라고 써
developer-cat.tistory.com
'내배캠Unreal_TIL > C++' 카테고리의 다른 글
| [TIL] 2026-01-29 | 약수 구하는 알고리즘 (1) | 2026.01.29 |
|---|---|
| [TIL] 2026-01-23 | <string> find, <algorithm> find (0) | 2026.01.23 |
| [TIL] 2026-01-19 | C++ Set 사용 (0) | 2026.01.19 |
| [TIL] 2026-01-15 | C++ 캐스트(cast) 연산자 (0) | 2026.01.15 |
| [TIL] 2026-01-12 | C++ 프로그래머스 행렬의 덧셈, 직사각형 별찍기, 최대공약수와 최소공배수 (0) | 2026.01.12 |