본문 바로가기

코딩 테스트/프로그래머스

(64)
[Level 1, C++] 2016년 시간을 계산해주는 방법을 찾아서 2016년 1월 1일 부터 해당 날짜까지 시간을 계산해서 요일을 구한다. #include #include #include #include using namespace std; string solution(int a, int b) { string answer = ""; time_t start, end; struct tm s_time; int tm_day, tm_hour, tm_min, tm_sec; double diff; string day[7] = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" }; s_time.tm_year = 2016 - 1900; s_time.tm_mon = 1 - 1; s_time.tm_mday = 1; s..
[Level 1, C++] 두 개 뽑아서 더하기 중복을 제거하는 함수인 unique와 erase를 같이 쓰면 쉽게 풀 수있다. #include #include #include using namespace std; vector solution(vector numbers) { vector answer; for(int i=0; i
[Level 1, C++] 3진법 뒤집기 파이썬에는 진법 계산하는 함수같은게 있던데 c++엔 그런게 없다. 그래서 그냥 직접 진법 계산하는걸로 만들었다. 직접 계산하면 앞뒤로 뒤집을 필요없으니 좋았다. #include #include #include #include using namespace std; int solution(int n) { int answer = 0; string str = ""; int i = 0; while (true) { str.append(to_string(n % 3)); n = n / 3; if( n == 0) break; } for (int i = 0; i < str.length(); i++) { cout
[Level 1, C++] 약수의 개수와 덧셈 다른사람들 풀이는 더 짧게 되어있어서 신기하게 느껴졌다. #include #include using namespace std; int solution(int left, int right) { int answer = 0; vector even; vector odd; vector temp; for (int i = left; i
[Level 1, C++] K번째수 잘라서 넣는 방법만 알면 쉽게 풀 수 있었다. #include #include #include using namespace std; vector solution(vector array, vector commands) { vector answer; for(int i = 0; i < commands.size(); i++) { vector copy; copy.assign(array.begin() + commands[i][0] - 1, array.begin() + commands[i][1]); sort(copy.begin(), copy.end()); answer.push_back(copy[commands[i][2] - 1]); } return answer; }
[Level 1, C++] 소수 만들기 문제를 봤을 때 "서로 다른 숫자 중 3개를 골라" 라고 나왔을 때 이건 조합을 이용해서 풀면 좋겠다고 싶었다. c++ STL에 조합을 만드는게 있었으면 좋았겠지만 순열을 만드는 것은 있다고 한다. 인터넷에 누가 올려주셔서 그냥 보고 따라했다. #include #include using namespace std; int solution(vector nums) { int answer = 0; vector arr; vectorv(nums.size() - 3, false); v.insert(v.end(), 3, true); do { vector temp; int sum = 0; for (int k = 0; k < nums.size(); k++) { if (v[k]) temp.push_back(nums[k]);..
[Level 1] 없는 숫자 더하기 제한사항으로 숫자가 정해져있어서 그냥 10칸 짜리 배열을 만들고 숫자가 있으면 해당하는 인덱스를 증가시키고 나중에 0인 인덱스만 구하는 방법으로 만들었다. 범위기반 for문을 사용했기 때문에 인덱스를 구할 때를 유의해야한다. #include #include #include using namespace std; int solution(vector numbers) { int answer = 0; vector arr(10); for(auto & n : numbers) { arr[n]++; } for(auto & n : arr) { if(n == 0) answer += &n - &*arr.begin(); // range based for에서 인덱스를 구하는 방법 } return answer; }
[Level 1] 신규 아이디 추천 프로그래머스 연습 문제 레벨 1 신규 아이디 추천 친구가 풀어보라고 추천해준 문제이다. 단계별 원하는 조건을 하나 하나 맞추다 보니 풀어지는 문제였다. #include #include #include using namespace std; void step_1(string &str) { transform(str.begin(), str.end(), str.begin(), ::tolower); } void step_2(string &str) { string temp; for (char& c : str) { if (islower(c) || isdigit(c) || c == '-' || c == '_' || c == '.') temp.push_back(c); } str = temp; } void step_3(st..